Categories of Questions

## Array Questions Microsoft

**Question 1. Shuffle the Array Leetcode Solution** The problem Shuffle the Array Leetcode Solution provides us with an array of length 2n. Here 2n refers that the array length is even. We are then told to shuffle the array. Here shuffling does not mean that we need to randomly shuffle the array but a specific way is ...

**Question 2. 3Sum Leetcode Solution** Problem Statement Given an array of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Notice: that the solution set must not contain duplicate triplets. Example #1 [-1,0,1,2,-1,4] ...

**Question 3. Insert Interval Leetcode Solution** The problem Insert Interval Leetcode Solution provides us with a list of some intervals and one separate interval. Then we are told to insert this new interval among the list of intervals. So, the new interval might be intersecting with intervals that are already in the list, or it might ...

**Question 4. Combination Sum Leetcode Solution** The problem Combination Sum Leetcode Solution provides us an array or list of integers and a target. We are told to find the combinations that can be made using these integers any number of times that add up to the given target. So more formally, we can use the given ...

**Question 5. Island Perimeter Leetcode Solution** Problem Statement In this problem, we are given a grid in form of a 2-D array. grid[i][j] = 0 represents there is water at that point and grid[i][j] = 1 represents land. Grid cells are connected vertically/horizontally but not diagonally. There is exactly one island (a connected component of land ...

**Question 6. Maximum Subarray Leetcode Solution** Problem Statement Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example nums = [-2,1,-3,4,-1,2,1,-5,4] 6 Explanation: [4,-1,2,1] has the largest sum = 6. nums = [-1] -1 Approach 1 (Divide and Conquer) In this approach ...

**Question 7. Find N Unique Integers Sum up to Zero Leetcode Solution** The problem Find N Unique Integers Sum up to Zero Leetcode Solution, provides us with an integer. It asks us to return n unique integers that sum up to 0. So, the question is pretty simple to understand. So, before diving into the solution. Let us take a look at ...

**Question 8. Partition Array Into Three Parts With Equal Sum Leetcode Solution** The problem Partition Array Into Three Parts With Equal Sum Leetcode Solution provides us with an array or vector and asks if there are three partitions possible of the sequence. Here, by partition we mean that is there two indices i, j such that the sum of elements from start ...

**Question 9. Find Common Characters Leetcode Solution** Problem Statement In this problem, we are given an array of strings. We need to print a list of all characters that appear in every string in the array(duplicates included). That is if a character appears 2 times in every string, but not 3 times, we need to have it ...

**Question 10. Find All Numbers Disappeared in an Array Leetcode Solution** Problem Statement In this problem, we are given an array of integers. It contains elements ranging from 1 to N, where N = size of the array. However, there are some elements that have disappeared and some duplicates are present in their place. Our goal is to return an array ...

**Question 11. Majority Element II Leetcode Solution** In this problem, we are given an array of integers. The goal is to find all the elements which occur more than ⌊N / 3⌋ time in the array where N = size of the array and ⌊ ⌋ is the floor operator. We need to return an array of ...

**Question 12. Relative Sort Array Leetcode Solution** In this problem, we are given two arrays of positive integers. All elements of the second array are distinct and are present in the first array. However, the first array can contain duplicate elements or elements that are not in the second array. We need to sort the first array ...

**Question 13. Pascal’s Triangle II Leetcode Solution** Problem Statement In this problem we have been given Row index(i) of the Pascal Triangle. We have to create a linear array containing the values of the ith row and return it. Row index starts from 0. We know that Pascal’s triangle is a triangle where each number is the ...

**Question 14. Unique Paths Leetcode Solution** The problem Unique Paths Leetcode Solution states that you are given two integers representing the size of a grid. Using the size of the grid, the length, and breadth of the grid. We need to find the number of unique paths from the top left corner of the grid to ...

**Question 15. Number of Good Pairs Leetcode Solution** Problem Statement In this problem an array of integers is given and we have to find out the count of total number of good pairs (a[i], a[j]) where a[i]=a[j]. Example nums = [1,2,3,1,1,3] 4 Explanation: There are 4 good pairs at indices (0,3), (0,4), (3,4), (2,5) . [1,1,1,1] 6 Explanation: ...

**Question 16. Find Lucky Integer in an Array Leetcode Solution** Problem statement In the problem ” Find Lucky Integer in an Array ” we are given an array where an integer is called lucky if its frequency in the array is equal to its value. Our task is to return the largest lucky number. If no such number exists we ...

**Question 17. Balanced Binary Tree Leetcode Solution** A binary tree is Height-balanced if the difference of heights of left and right subtree of every node in the tree is at most 1. In this problem, we are going to check for a balanced binary tree. Example 2 / 1 / 4 Not balanced 1 / \ 2 ...

**Question 18. Merge Sorted Arrays Leetcode Solution** In the problem “Merge Sorted Arrays”, we are given two arrays sorted in non-descending order. The first array is not fully filled and has enough space to accommodate all elements of the second array as well. We have to merge the two arrays, such that the first array contains elements ...

**Question 19. Search in Rotated Sorted Array Leetcode Solution** Consider a sorted array but one index was picked and the array was rotated at that point. Now, once the array has been rotated you are required to find a particular target element and return its index. In case, the element is not present, return -1. The problem is generally ...

**Question 20. Search Insert Position Leetcode Solution** In this problem, we are given a sorted array and a target integer. We have to find its Search Insert Position. If the target value is present in the array, return its index. Return the index at which the target should be inserted so as to keep the order sorted(in ...

**Question 21. Plus One Leetcode Solution** Problem statement In the problem ” Plus One” we are given an array where each element in the array represents a digit of a number. The complete array represents a number. The zeroth index represents the MSB of the number. We can assume that there is no leading zero in ...

**Question 22. Kth largest element in an Array Leetcode Solutions** In this problem, we have to return the kth largest element in an unsorted array. Note that the array can have duplicates. So, we have to find the Kth largest element in the sorted order, not the distinct Kth largest element. Example A = {4 , 2 , 5 , 3 ...

**Question 23. Kth Missing Positive Number Leetcode Solution** Problem statement In the problem “Kth Missing Positive Number” we are given an array arr, which is sorted in strictly increasing order and a number k. Our task is to find out the Kth positive missing number in the array. Example arr = [1,2,3,4], k = 2 6 Explanation: As ...

**Question 24. Guess Number Higher or Lower II** Problem Statement “Guess Number Higher or Lower II” states that we are going to play a game that is called Guess Game. The game says that I pick a number from 1 to n. Whenever you guess the number which I have not picked, I m going to say you ...

**Question 25. Queries for Number of Distinct Elements in a Subarray** We have given an array of integer and a number of queries and we have to find out the number of all the distinct elements we have within the given range, the query consists of two numbers left and right, this is the given range, with this given range we ...

**Question 26. Minimum swaps required to bring all elements less than or equal to k together** The problem “Minimum swaps required to bring all elements less than or equal to k together” states that you have an integer array. The problem statement asks to find out the smallest count of swaps that will be required to get the elements together which are less than or equal ...

**Question 27. Find First and Last Position of Element in Sorted Array Leetcode Solution** Problem statement In this article titled “Find First and Last Position of Element in Sorted Array Leetcode Solution,” we will discuss the solution to a leetcode problem. In the given problem we are given an array. We are also given a target element. Elements in the array are sequenced in ...

**Question 28. Best Time to Buy and Sell Stock II Leetcode Solution** Problem statement In the problem “Best Time to Buy and Sell Stock II,” we are given an array where each element in the array contains the price of the given stock on that day. The definition of the transaction is buying one share of stock and selling that one share ...

**Question 29. Find Sum of all unique sub-array sum for a given array** Suppose you have an array of integers. The problem “Find Sum of all unique sub-array sum for a given array” asks to find out the sum of all unique sub-arrays (Sub-array sum is the sum of each sub-array’s elements). By unique sub-array sum, we meant to say that no sub-array ...

**Question 30. Longest subarray not having more than K distinct elements** The problem “Longest subarray not having more than K distinct elements” states that suppose you have an array of integers, the problem statement asks to find out the longest sub-array that having not greater than k different elements. Example arr[] = {4, 3, 5, 2, 1, 2, 0, 4, 5} ...

**Question 31. Construct Binary Tree from given Parent Array representation** The problem “Construct Binary Tree from given Parent Array representation” states that you are given an array. This input array represents a binary tree. Now you need to construct a binary tree on the basis of this input array. The array stores the index of parent node at each index. ...

**Question 32. Find any one of the multiple repeating elements in read only array** the problem “Find any one of the multiple repeating elements in read only array” states that suppose you are given a read-only array of size (n+1). An array is containing the integers from 1 to n. Your task is to find out any one of the repeated elements in the ...

**Question 33. Find four elements that sum to a given value (Hashmap)** The problem “Find four elements that sum to a given value (Hashmap)” states that suppose, you have an integer array and a number called sum. The problem statement asks to determine if four elements present in the array which sums up to the given value “sum”. If true, then function ...

**Question 34. Longest subsequence such that difference between adjacents is one** The problem “Longest subsequence such that difference between adjacents is one” states that you are given an integer array. Now you need to find the length of longest subsequence such that the difference of adjacent elements is 1. Example 1 2 3 4 7 5 9 4 6 Explanation As ...

**Question 35. Print all subarrays with 0 sum** You are given an integer array, your task is to print all the possible sub-arrays with sum is equal to 0. So we need to Print all subarrays with 0 sum. Example arr[] = {-2, 4, -2, -1, 1, -3, 1, 5, 7, -11, -6} Sub-Array found from 0 index ...

**Question 36. Longest Bitonic Subsequence** Suppose you have an array of integers, the problem statement asks to find out the longest bitonic subsequence. The bitonic sequence of an array is considered as the sequence which first increases and then decreases. Example arr[] = {1,4,2,76,43,78,54,32,1,56,23} 7 Explanation 1 ⇒ 4 ⇒ 76 ⇒ 78 ⇒ 54 ...

**Question 37. Check in binary array the number represented by a subarray is odd or even** The problem “Check in binary array the number represented by a subarray is odd or even” states that you are given a binary array and a range. The array consists of the number in the form of 0s and 1s. The problem statement asks to find out the number represented ...

**Question 38. Gold Mine Problem** Problem Statement The “Gold Mine problem” states that you are given a 2D grid having some non-negative coins placed in each cell of the given grid. Initially, the miner is standing at the first column but there is no restriction on the row. He can start in any row. The ...

**Question 39. Longest Increasing Consecutive Subsequence** Subsequences are another topic loved by interviewers. Tweaking them around can always give them new opportunities for testing candidates. It can check the candidate’s ability to think and analyze things and come up with the best and optimal solutions. Today we are solving a subsequence problem that will be doing ...

**Question 40. Best Time to Buy and Sell Stock** Problem Statement The problem “Best Time to Buy and Sell Stock” states that you are given an array of prices of length n, where the ith element stores the price of stock on ith day. If we can make only one transaction, that is, to buy on one day and ...

**Question 41. Top K Frequent Elements** Problem Statement In top K frequent elements we have given an array nums[], find the k most frequently occurring elements. Examples nums[] = {1, 1, 1, 2, 2, 3} k = 2 1 2 nums[] = {1} k = 1 1 Naive Approach for Top K Frequent Elements Build ...

**Question 42. Sort an array according to the order defined by another array** Problem Statement You are given two arrays of integers arr1[] and arr2[]. The problem “Sort an array according to the order defined by another array” asks to sort the first array according to the second array so that the numbers in first array will be relatively sorted off all the ...

**Question 43. Minimum time required to rot all oranges** Problem Statement The problem “Minimum time required to rot all oranges” states that you are given a 2D array, every cell has one of the three possible values 0, 1 or 2. 0 means an empty cell. 1 means a fresh orange. 2 means a rotten orange. If a rotten ...

**Question 44. Maximum Product Subarray** Problem Statement The problem “Maximum Product Subarray” states that you are given an array of integer containing both positive and negative numbers. The problem statement asks to find out the maximum product of the sub-array. Example arr[] = { 2, -2, 3, 5} 15 Explanation The elements in the sub-array ...

**Question 45. Find Minimum In Rotated Sorted Array** Problem Statement “Find Minimum In Rotated Sorted Array” states that you are given a sorted array of size n which is rotated at some index. Find the minimum element in the array. Example a[ ] = {5, 1, 2, 3, 4} 1 Explanation: If we arrange the array in sorted ...

**Question 46. Implementation of Deque using circular array** Problem Statement “Implementation of Deque using circular array” asks to implement the following functions of a Deque(Doubly Ended Queue) using circular array, insertFront(x) : insert an element x at the front of Deque insertRear(x) : insert an element x at the rear of Deque deleteFront() : delete an element from ...

**Question 47. Double the first element and move zero to end** Problem Statement Suppose you have an array of integers. Here “0” is not a number which is considered as an input. It is not valid input here. The problem “Double the first element and move zero to end” asks to rearrange the array in such a way if a number ...

**Question 48. Find the first repeating element in an array of integers** Problem Statement Find the first repeating element in an array of integers problem states that you are given an array of integer. It asks to find out the first repeating element from the array and print that number. Example arr[] = {2,6,9,3,1,9,1} 9 Explanation: In the given array there are ...

**Question 49. Check given array of size n can represent BST of n levels or not** Problem Statement Given an array with n elements, check given array of size n can represent BST of n levels or not. That is to check whether the binary search tree constructed using these n elements can represent a BST of n levels. Examples arr[] = {10, 8, 6, 9, ...

**Question 50. Largest rectangular sub-matrix whose sum is 0** Problem Statement Find the maximum size sub-matrix in a 2D array whose sum is zero. A sub-matrix is nothing but a 2D array inside of the given 2D array. So, you have a matrix of signed integers, you need to calculate the sum of sub-matrices and find the matrix with ...

**Question 51. Maximum Sum Increasing Subsequence** Problem Statement You are given an array of integers. Your task is to find out the maximum sum subsequence within the array in such a way that the numbers in subsequence should be ordered in a sorted manner in increasing order. A subsequence is nothing but a sequence that we ...

**Question 52. Largest Sum Contiguous Subarray** Problem Statement You are given an array of integers. The problem statement asks to find out the largest sum contiguous subarray. This means nothing but to find a subarray (continuous elements) which has the largest sum among all other subarrays in the given array. Example arr[] = {1, -3, 4, ...

**Question 53. Matrix Chain Multiplication** In the matrix chain multiplication II problem, we have given the dimensions of matrices, find the order of their multiplication such that the number of operations involved in multiplication of all the matrices is minimized. Consider you have 3 matrices A, B, C of sizes a x b, b x ...

**Question 54. Sorted Array to Balanced BST** In sorted array to balanced BST problem, we have given an array in sorted order, construct a Balanced Binary Search Tree from the sorted array. Examples Input arr[] = {1, 2, 3, 4, 5} Output Pre-order : 3 2 1 5 4 Input arr[] = {7, 11, 13, 20, 22, ...

**Question 55. Subset Leetcode** In Subset Leetcode problem we have given a set of distinct integers, nums, print all subsets (the power set). Note: The solution set must not contain duplicate subsets. An array A is a subset of an array B if a can be obtained from B by deleting some (possibly, zero ...

**Question 56. Shuffle an Array** Given an array or set which contains n elements. Here the elements are unique or there is no repetition. Shuffle an array(or a set) of numbers without duplicates. Example // Init an array with set 2, 4, 3 and 1. int[] nums = {2, 4, 3, 1}; Shuffle object = ...

**Question 57. Dividing Array into Pairs With Sum Divisible by K** The dividing array into pairs with sum divisible by K is a problem which is asked in interviews with various tweaks now and then. Those who know me know my habit of converting these problems into stories. In this article let us look into this problem. Situation To Understand The ...

**Question 58. Count Distinct Elements in Every Window of Size K** Subsets are something which we have been dealing with for some time now. In the last episode, we covered the number of subsets we could make with distinct even numbers. This time we count distinct elements in every window of size K. Section-1 About the problem. Given an unsorted array ...

**Question 59. Word Search** Word search is something like the word-finding puzzles at some time in our life. Today I bring to the table a modified crossword. My readers must be a bit perplexed as to what I am talking about. Without wasting any more time let us get to the problem statement Can ...

**Question 60. Insert Delete GetRandom** In Insert Delete GetRandom problem we need to design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from the current set ...

**Question 61. Merge Overlapping Intervals** In merge overlapping intervals problem we have given a collection of intervals, merge and return all overlapping intervals. Example Input : [[2, 3], [3, 4], [5, 7]] Output: [[2, 4], [5, 7]] Explanation: We can merge [2, 3] and [3, 4] together to form [2, 4] Approach for finding Merge ...

**Question 62. Median of Two Sorted Arrays** Given two sorted arrays A and B of size n and m respectively. Find the median of the final sorted array obtained after merging the given two arrays or in other words, we say that find median of two sorted arrays. ( Expected time complexity: O(log(n)) ) Approach 1 for ...

**Question 63. Maximum Product Subarray** In the maximum product subarray problem, we have given an array of integers, find the contiguous sub-array with atleast one element which has the largest product. Example Arr=[ 0, -1, 0 ,1 ,2, -3] Maximum product = 2 Arr=[-1, -1, -1] Maximum product = -1 Arr=[0, -1, 0, -2, 0] ...

**Question 64. Minimum Size Subarray Sum** Given an array nums of a positive integer and a sum s, find the minimum size of a contiguous subarray of nums such that whose sum equals to or greater than s(given value). Example Input: nums[] = {2, 3, 1, 2, 4, 3} s = 7 Output: 2 {Subarray [4, ...

**Question 65. Search an Element in Sorted Rotated Array** In search in sorted rotated array problem we have given a sorted and rotated array and an element, check if the given element is present in the array or not. Examples Input nums[] = {2, 5, 6, 0, 0, 1, 2} target = 0 Output true Input nums[] = {2, ...

**Question 66. Maximum Product Subarray** Given an array of n integers, find the maximum product obtained from a contiguous subarray of the given array. Examples Input arr[] = {-2, -3, 0, -2, -40} Output 80 Input arr[] = {5, 10, 6, -2, 1} Output 300 Input arr[] = {-1, -4, -10, 0, 70} Output 70 ...

**Question 67. Set Matrix Zeroes** In the set matrix zeroes problem, we have given a (n X m) matrix, if an element is 0, set its entire row and column 0. Examples Input: { [1, 1, 1] [1, 0, 1] [1, 1, 1] } Output: { [1, 0, 1] [0, 0, 0] [1, 0, 1] ...

**Question 68. 3 Sum** In 3 Sum problem, we have given an array nums of n integers, find all the unique triplets that sum up to 0. Example Input: nums = {-1, 0, 1, 2, -1, -4} Output: {-1, 0, 1}, {-1, 2, -1} Naive Approach for 3 Sum problem The Brute force approach ...

**Question 69. Find The Duplicate Number** Given an array nums containing (n + 1) elements and every element is between 1 to n. If there is only one duplicate element, find the duplicate number. Examples Input: nums = {1, 3, 4, 2, 2} Output: 2 Input: nums = {3, 1, 3, 4, 2} Output: 3 Naive ...

**Question 70. Minimum Path Sum** In the minimum path sum problem, we have given “a × b” matrix consisting of non-negative numbers. Your task is to find the path from top left to right bottom which minimizes the sum consisting of all the numbers which come in a path you found. Note: You can only move ...

**Question 71. Find the Duplicate Element** Given an array of integers of size n+1 where each element of the array is between 1 and n (inclusive), there is one duplicate element in the array, find the duplicate element. Brute force method – Approach 1 for Find the Duplicate Element For every ith element run a loop ...

**Question 72. Next Greater Frequency Element** In the next greater frequency element problem, we have given an array a[ ] of size n containing numbers. For each number in the array print, the number to it’s right in an array with a frequency greater than that of the current number. Example Input a[] = {1, 1, ...

**Question 73. Trapping Rain Water** In Trapping Rain Water problem we have given N non-negative integers representing an elevation map and the width of each bar is 1. We have to find the amount of water that can be trapped in the above structure. Example Let’s understand that by an example For the above elevation ...

**Question 74. Jump Game** In jump game we have given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example Input: arr = [2,3,1,1,4] ...

**Question 75. Combination Sum** In combination sum problem we have given an array of positive integers arr[] and a sum s, find all unique combinations of elements in arr[] where the sum of those elements is equal to s. The same repeated number may be chosen from arr[] an unlimited number of times. Elements ...

**Question 76. Search in Sorted Rotated Array** An element search in sorted rotated array can be found using binary search in O(logn) time. The objective of this post is to find a given element in a sorted rotated array in O(logn) time. Some example of a sorted rotated array is given. Example Input : arr[] = {7,8,9,10,1,2,3,5,6}; ...

**Question 77. Unique Paths** A m x n 2D grid is given and you are standing at the topmost and leftmost cell in the grid. i.e. the cell located at (1,1). Find the number of unique paths that can be taken to reach a cell located at (m,n) from the cell located at (1,1) ...

**Question 78. Maximum Subarray** In the Maximum Subarray problem we have given an integer array nums, find the contiguous sub array which has the largest sum and print the maximum sum subarray value. Example Input nums[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4} Output 6 Algorithm The goal is to find ...

**Question 79. Merging Intervals** In merging intervals problem we have given a set of intervals of the form [l, r], merge the overlapping intervals. Examples Input {[1, 3], [2, 6], [8, 10], [15, 18]} Output {[1, 6], [8, 10], [15, 18]} Input {[1, 4], [1, 5]} Output {[1, 5]} Naive Approach for merging intervals ...

**Question 80. Peak Index in a Mountain Array** What is Peak Index in a Mountain Array Problem? An array can be said as a Mountain Array if it shows the following properties: The length of the given array is should be greater than or equal to 3 LENGTH >=3. There can be only one peak or largest element ...

**Question 81. Maximum size subarray sum equals k** In Maximum size subarray sum equals k we have given an array of integers and a value k. You have to find the length of the longest subarray whose sum is equal to k. If no such subarray exists then return 0. One approach is to use hashtable and check ...

**Question 82. Missing Number** In Missing Number problem we have given an array of size N containing a number from 0 to N. All the values in the array are unique. We need to find the missing number which is not present in the array and that number lies between 0 to N. Here ...

**Question 83. Merge Sorted Array** In merge sorted array problem we have given two sorted arrays in increasing order. In input first, we have given the number initialized to array1 and array2. These two-number are N and M. The size of array1 is equal to the sum of N and M. In array 1 first ...

**Question 84. Rotate Array** Rotate array is a problem in which we have given an array of size N. We have to rotate the array in the right direction. Each element shift by one position right and last element of the array come to the first position. So, we have given a value K ...

**Question 85. Matrix Chain Multiplication using Dynamic Programming** Matrix Chain Multiplication is a method in which we find out the best way to multiply the given matrices. We all know that matrix multiplication is associative(A*B = B*A) in nature. So, we have a lot of orders in which we want to perform the multiplication. Actually, in this algorithm, ...

**Question 86. Subarray Sum Equals k** Given an integer array and an integer k. Find total number of contiguous subarrays of given array whose sum of elements is equal to k. Example Input 1: arr[] = {5,0,5,10,3,2,-15,4} k = 5 Output: 7 Input 2: arr[] = {1,1,1,2,4,-2} k = 2 Output: 4 Explanation : consider example-1 ...

**Question 87. Merge K Sorted Arrays and Print Sorted Output** Problem Statement In the “Merge K Sorted Arrays and Print Sorted Output” problem we have given k sorted arrays of different size. Write a program to merge those arrays and prints the final sorted array as output. Input Format The first line containing an integer n. Next n lines containing ...

**Question 88. Find the Minimum Element in a Sorted and Rotated Array** Problem Statement In the “Find the Minimum Element in a Sorted and Rotated Array” problem we have given a sorted array a[]. This array is rotated at some unknown point, find the minimum element in this array. Input Format The first and only one line containing an integer value n. ...

**Question 89. Stock Buy Sell to Maximize Profit** Problem Statement In the “Stock Buy Sell to Maximize Profit” problem we have given an array that contains stock price on each day, find the maximum profit that you can make by buying and selling in those days. Here, we can buy and sell multiple times but only after selling ...

**Question 90. Merge Overlapping Intervals II** Problem Statement In the “Merge Overlapping Intervals II” problem we have given a set of intervals. Write a program that will merge the overlapping intervals into one and print all the non-overlapping intervals. Input Format The first line containing an integer n. Second-line containing n pairs where each pair is ...

**Question 91. Maximum Subarray Sum using Divide and Conquer** Problem Statement In the “Maximum Subarray Sum using Divide and Conquer” problem we have given an array of both positive and negative integers. Write a program that will find the largest sum of the contiguous subarray. Input Format The first line containing an integer N. Second-line containing an array of ...

**Question 92. Pancake Sorting Problem** Problem Statement “Pancake Sorting Problem” is based on pancake sorting. Given an unsorted array, we need to write a program that uses only flip operation to sort the array. Flip is the operation that reverses the array. Input Format The first line containing an integer N. Second-line containing N space-separated ...

**Question 93. Pancake Sorting** Problem Statement In the “Pancake Sorting” problem we have given an array of integers A[]. Sort the array by performing a series of pancake flips. In one pancake flip we do the following steps: Choose an integer k where 1 <= k <= arr.length. Reverse the sub-array arr[0…k-1] (0-indexed). Input ...

**Question 94. Arrange given Numbers to Form the Biggest Number II** Problem Statement In the “Arrange given Numbers to Form the Biggest Number II” problem, we have given an array of positive integers. Arrange them in such a way that the arrangement will form the largest value. Input Format The first and only one line containing an integer n. Second-line containing ...

**Question 95. Shuffle a given Array** Problem Statement In the “Shuffle a given Array” problem we have given an array of integers. Write a program that shuffles the given array. That is, it will shuffle the elements in the array randomly. Input Format The first line containing an integer n. Second-line containing n space-separated integer Output ...

**Question 96. Find the Row with Maximum Number of 1’s** Problem Statement In the “Find the Row with Maximum Number of 1’s” problem we have given a matrix(2D array) containing binary digits with each row sorted. Find the row which has the maximum number of 1’s. Input Format The first line containing two integers values n, m. Next, n lines ...

**Question 97. Maximum Product Subarray II** Problem Statement In the “Maximum Product Subarray II” problem we have given an array consisting of positive, negative integers, and also zeroes. We need to find the maximum product of the subarray. Input Format The first line containing an integer N. Second-line containing N space-separated integers. Output Format The only ...

**Question 98. Maximum Sum Increasing Subsequence** Problem Statement In the “Maximum Sum Increasing Subsequence” problem we have given an array. Find the sum of the maximum subsequence of the given array, that is the integers in the subsequence are in sorted order. A subsequence is a part of an array which is a sequence that is ...

**Question 99. Implement Two Stacks in an Array** Problem Statement In the “Implement Two Stacks in an Array” problem we have to implement two stacks in an array such that, if the user wants to push an element in either of two stacks then there should not be an error till the array gets full. Example Push 5 ...

**Question 100. Number of Smaller Elements on Right Side** Problem Statement In the “Number of Smaller Elements on Right Side” problem, we have given an array a[]. Find the number of smaller elements that are on the right_side of each element. Input Format The first and only one line containing an integer N. Second-line containing N space-separated integers. Output ...

**Question 101. Elements Appear more than N/K times in Array** Problem Statement In the “Elements Appear more than N/K times in Array” problem we have given an integer array of size n. Find the elements which appear more than n/k times. Where k is the input value. Input Format The first and only one line containing two integers N and ...

**Question 102. Find the Peak Element from an Array** Problem Statement In the “Find the Peak Element from an Array” problem we have given an input array of integers. Find a peak element. In an array, an element is a peak element, if the element is greater than both the neighbours. For corner elements, we can consider the only ...

**Question 103. Find the Maximum Repeating Number in Array** Problem Statement In the “Find the Maximum Repeating Number in Array” problem we have given an unsorted array of size N. Given array contains numbers in range {0, k} where k <= N. Find the number that is coming the maximum number of times in the array. Input Format The ...

**Question 104. First Circular Tour to Visit all the Petrol Bunks** In the first circular tour to visit all the petrol bunks problem the statement is such that there is a circle with n petrol pumps on the circle. Every petrol pump has a pair of data. The first value is the amount of petrol pump has and the second is ...

**Question 105. Four Elements that Sum to Given** Problem Statement In four elements that sum to a given problem, we have given an array containing N elements that may be positive or negative. Find the set of four elements whose sum is equal to given value k. Input Format First-line containing an integer N. Second-line containing an array ...

**Question 106. Partition Problem** Problem Statement In the Partition problem, we have given a set that contains n elements. Find whether the given set can be divided into two sets whose sum of elements in the subsets is equal. Example Input arr[] = {4, 5, 11, 9, 8, 3} Output Yes Explanation The array ...

**Question 107. The Celebrity Problem** Problem Statement In the celebrity problem there is a room of N people, Find the celebrity. Conditions for Celebrity is- If A is Celebrity then Everyone else in the room should know A. A shouldn’t know anyone in the room. We need to find the person who satisfies these conditions. ...

**Question 108. Subarray with Given Sum** Problem Statement In the subarray with the given sum problem, we have given an array containing n positive elements. We have to find the subarray in which the sum of all the elements of the subarray equal to a given_sum. Subarray is obtained from the original array by deleting some ...

**Question 109. Maximum Element in an Array which is Increasing and then Decreasing** Problem Statement In the given array which contains n elements. Elements are stored in such a way that first k elements are in increasing order and then n-k elements in decreasing from there, we need to find the maximum element in the array. Example a) Input array : [15, 25, ...

**Question 110. Find the Lost Element From a Duplicated Array** Problem Statement Given two arrays A and B, one array is a duplicate of the other except one element. The one element is missing from either A or B. we need to find the lost element from a duplicated array. Example 5 1 6 4 8 9 6 4 8 ...

**Question 111. Subarray and Subsequence** Problem Statement In the subarray and subsequence problem, we have to print all the subarrays and subsequences for a given array. Generate all possible non-empty subarrays. A subarray is commonly defined as a part or section of an array in which the contiguousness is based on the index. The subarray ...

**Question 112. Merge Two Sorted Arrays** Problem Statement In merge two sorted arrays problem, we have given two input sorted arrays, we need to merge these two arrays such that the initial numbers after complete sorting should be in the first array and remaining in the second array. Example Input A[] = {1, 3, 5, 7, ...

**Question 113. Count of Triplets With Sum Less than Given Value** Problem Statement We have given an array containing N number of elements. In the given array, Count the number of triplets with a sum less than the given value. Example Input a[] = {1, 2, 3, 4, 5, 6, 7, 8} Sum = 10 Output 7 Possible triplets are : ...

**Question 114. Next Greater Element in an Array** Problem Statement Given an array, we will find the next greater element of each element in the array. If there is no next greater element for that element then we will print -1, else we will print that element. Note: Next greater element is the element that is greater and ...

**Question 115. Merging Two Sorted Arrays** Problem Statement In merging two sorted arrays problem we have given two sorted arrays, one array with size m+n and the other array with size n. We will merge the n sized array into m+n sized array and print the m+n sized merged array. Example Input 6 3 M[] = ...

**Question 116. Find Element Using Binary Search in Sorted Array** Problem Statement Given a sorted array, Find element using binary search in the sorted array. If present, print the index of that element else print -1. Example Input arr[] = {1, 6, 7, 8, 9, 12, 14, 16, 26, 29, 36, 37, 156} X = 6 //element to be searched ...

**Question 117. Find Triplet in Array With a Given Sum** Problem Statement Given an array of integers, find the combination of three elements in the array whose sum is equal to a given value X. Here we will print the first combination that we get. If there is no such combination then print -1. Example Input N=5, X=15 arr[] = ...

**Question 118. Find Duplicates in an Array in Most Efficient Way** Problem Statement Display all the elements which are duplicates in the most efficient way in O(n) and O(1) space. Given an array of size n which contains numbers from range 0 to n-1, these numbers can occur any number of times. Find duplicates in an array in the most efficient ...

**Question 119. Sort 0s 1s and 2s in an Array** Problem Statement Given an array containing N elements where elements of the array are 0,1 or 2. Sort or Segregate 0s 1s and 2s in an array. Arrange all zeros in the first half, all ones in the second half and all twos in the third half. Example Input 22 ...

**Question 120. Smallest Positive Number Missing in an Unsorted Array** Problem Statement In the given unsorted array find the smallest positive number missing in an unsorted array. A positive integer doesn’t include 0. We can modify the original array if needed. The array may contain positive and negative numbers. Example a. Input array : [3, 4, -1, 0, -2, 2, 1, ...

**Question 121. Move All the Zeros to the End of the Given Array** Problem Statement In the given array move all the zeros which are present in the array to the end of the array. Here there is always a way exist to insert all the number of zeroes to the end of the array. Example Input 9 9 17 0 14 0 ...

**Question 122. Count Number of Occurrences in a Sorted Array** Problem Statement In the “Count Number of Occurrences in a Sorted Array” problem, we have given a sorted array. Count the number of occurrences or frequency in a sorted array of X where X is an integer. Example Input 13 1 2 2 2 2 3 3 3 4 4 ...

**Question 123. Find Smallest Missing Number in a Sorted Array** Problem Statement In the “Find Smallest Missing Number in a Sorted Array” problem we have given an integer array. Find the smallest missing number in N sized sorted array having unique elements in the range of 0 to M-1, where M>N. Example Input [0, 1, 2, 3, 4, 6, 7, ...

**Question 124. First Repeating Element** Problem Statement We have given an array that contains n integers. We have to find the first repeating element in the given array. If there is no repeated element then print “No repeating integer found”. Note: Repeating elements are those elements that come more than once. (Array may contain duplicates) ...

**Question 125. A Product Array Puzzle** Problem Statement In a product array puzzle problem we need to construct an array where the ith element will be the product of all the elements in the given array except element at the ith position. Example Input 5 10 3 5 6 2 Output 180 600 360 300 900 ...

**Question 126. Find All Pairs With a Given Difference** Problem Statement We have given an array of containing different elements or no repeated elements present in the array. Find all pairs with a given difference. If there is no any pair with given different then print “No pair with given different”. Example Input 10 20 90 70 20 80 ...

**Question 127. Find the first Repeating Number in a Given Array** Problem Statement There can be multiple repeating numbers in an array but you have to find the first repeating number in a given array (occurring the second time). Example Input 12 5 4 2 8 9 7 12 5 6 12 4 7 Output 5 is the first repeating element ...

**Question 128. Majority Element** Problem Statement Given a sorted array, we need to find the majority element from the sorted array. Majority element: Number occurring more than half the size of the array. Here we have given a number x we have to check it is the majority_element or not. Example Input 5 2 ...

**Question 129. Find the Missing Number** Problem Statement In finding the missing number from an array of 1 to N numbers we have given an array that contains N-1 numbers. One number is missing from an array of numbers from 1 to N. We have to find the missing number. Input Format First-line containing an integer ...

## String Questions Microsoft

**Question 130. Minimum Number of Steps to Make Two Strings Anagram Leetcode Solutions** Problem Statement In this problem, we are given two strings ‘s’ & ‘t’ consisting of lower-case English characters. In one operation, we can choose any character in string ‘t’ and change it to some other character. We need to find the minimum number of such operations to make ‘t’ an ...

**Question 131. Isomorphic Strings Leetcode Solution** Problem Statement In this problem, we are given two strings, a and b. Our goal is to tell whether the two strings are isomorphic or not. Two strings are called isomorphic if and only if the characters in the first string can be replaced by any character(including itself) at all ...

**Question 132. Is Subsequence Leetcode Solution** Problem Statement In this problem, we are given two different strings. The goal is to find out whether the first string is a subsequence of the second. Examples first string = "abc" second string = "mnagbcd" true first string = "burger" second string = "dominos" false Approach(Recursive) This is easy ...

**Question 133. Add Binary Leetcode Solution** Problem Statement Given two binary strings a and b, we have to add these two strings and then return the result as a binary string. Binary string are the strings that contains only 0s and 1s. Example a = "11", b = "1" "100" a = "1010", b = "1011" "10101" Approach For adding two ...

**Question 134. Valid Palindrome Leetcode Solution** Problem Statement Given a string, we have to determine if it is a palindrome, considering only alphanumeric characters i.e. numbers and alphabets only. We also have to ignore cases for alphabet characters. Example "A man, a plan, a canal: Panama" true Explanation: “AmanaplanacanalPanama” is a valid palindrome. "race a car" ...

**Question 135. Roman to Integer Leetcode Solution** In the problem “Roman to Integer”, we are given a string representing some positive integer in its Roman numeral form. Roman numerals are represented by 7 characters that can be converted to integers using the following table: Note: The integer value of the given roman numeral will not exceed or ...

**Question 136. Reformat The String Leetcode Solution** Problem Statement In this problem, we are given an alphanumeric string i.e. the string has only lowercase alphabets (a-z) and digits(0-9). We are required to return any permutation of this string, in which there is no consecutive alphabet in it or no consecutive digits. If no such permutation is there, ...

**Question 137. Multiply Strings Leetcode Solution** The problem Multiply Strings Leetcode solution asks us to multiply two strings which are given to us as input. We are required to print or return this result of multiplying to the caller function. So to put it more formally given two strings, find the product of the given strings. ...

**Question 138. Integer to Roman Leetcode Solution** In this problem, we are given an integer and are required to convert into roman numeral. Thus the problem is generally referred to as “Integer to Roman” and this is Integer to Roman Leetcode Solution. If someone does not know about Roman numerals. In the old times, people did not ...

**Question 139. Group Anagrams** We have to find out the group anagrams of the given words. This means for each word we are going to sort it and store it as a key and original input which is not sorted as a value and if any other input has the same value as a ...

**Question 140. Integer to English words** In problem “Integer to English words” we have given a non-negative integer and the tasks to convert that integer into its numerical words or we get an input of a number, any number, and our task is to represent that number in a string form. Let’s see one example, the ...

**Question 141. Letter Combinations of a Phone Number** In letter combinations of a phone number problem, we have given a string containing numbers from 2 to 9. The problem is to find all the possible combinations that could be represented by that number if every number has some letters assigned to it. The assignment of the number is ...

**Question 142. Longest Substring Without Repeating Characters** Given a string, we have to find the length of the longest substring without repeating characters. Let’s look into a few examples: Example pwwkew 3 Explanation: Answer is “wke” with length 3 aav 2 Explanation: Answer is “av” with length 2 Approach-1 for Longest Substring Without Repeating Characters Brute Force ...

**Question 143. Palindrome Permutation** Problem Statement The problem “Palindrome Permutation” states that you are given a string. Check if it can be rearranged to form a palindromic string. Example superdupers yes Explanation The given input string can be rearranged to superdrepus. It is a palindromic string. So our answer to this example is yes. ...

**Question 144. Text Justification** Problem Statement The problem “Text Justification” states that you are given a list s[ ] of type string of size n and an integer size. Justify the text such that each line of text consists of size number of characters. You can use space(‘ ‘) as a character to complete ...

**Question 145. Queue based approach for first non-repeating character in a stream** Problem Statement The problem “Queue based approach for first non-repeating character in a stream” states that you are given a stream containing lower case characters, find the first non-repeating character whenever a new character is added to the stream, and if there is no non-repeating character return -1. Examples aabcddbe ...

**Question 146. Palindrome Substring Queries** Problem Statement The problem “Palindrome Substring Queries” states that you are given a String and some queries. With those queries, you have to determine if the formed substring from that query is a palindrome or not. Example String str = "aaabbabbaaa" Queries q[] = { {2, 3}, {2, 8},{5, 7}, ...

**Question 147. Palindrome Partitioning** Problem Statement Given a string, find the minimum number of cuts required such that all the substrings of partitions are palindromes. Since we are cutting our original string into different partitions such that all the substrings are palindromes, we call this problem the Palindrome Partition Problem. Example asaaaassss 2 Explanation: ...

**Question 148. Reverse words in a string** Problem Statement “Reverse words in a string” states that you are given a string s of size n. Print the string in reverse order such that the last word becomes the first, second last becomes the second, and so on. Hereby string we refer to a sentence containing words instead ...

**Question 149. Mobile Numeric Keypad Problem** Problem Statement In the mobile numeric keypad problem, we consider a numeric keypad. We need to find all number of possible numeric sequences of given length such that you are only allowed to press buttons which are top, down, left, and right of the current button. You are not allowed ...

**Question 150. Decode Ways** In Decode Ways problem we have given a non-empty string containing only digits, determine the total number of ways to decode it using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Example S = “123” Number of ways to decode this string is 3 If we ...

**Question 151. Edit Distance** In the edit distance problem we have to find the minimum number of operations required to convert a string X of length n to another string Y of length m. Operations allowed: Insertion Deletion Substitution Example Input: String1 = “abcd” String2 = “abe” Output: Minimum operations required is 2 ( ...

**Question 152. Longest Palindromic Subsequence** In the longest palindromic subsequence problem we have given a string, find the length of the longest palindromic subsequence. Examples Input: TUTORIALCUP Output: 3 Input: DYNAMICPROGRAMMING Output: 7 Naive Approach for Longest Palindromic Subsequence The naive approach to solve the above problem is to generate all the subsequences of the ...

**Question 153. KMP Algorithm** KMP(Knuth-Morris-Pratt) algorithm is used for pattern searching in a given string. We are given a string S and a pattern p, our goal is to determine whether or not the given pattern is present in the string. Example Input: S = “aaaab” p = “aab” Output: true Naive Approach The ...

**Question 154. Fizz Buzz** The problem name might seem fuzzy. Fizz Buzz is a game with which children are taught about the division. So, without much hassle let’s clear the buzz around it. Problem Statement Let us write a program where for multiples of 3 you print “Fizz”, for the multiples of 5 “Buzz” ...

**Question 155. Fizz Buzz Leetcode** In Fizz Buzz problem we have given a number n, print the string representation of numbers from 1 to n with the given conditions: Print “Fizz” for multiples of 3. Print “Buzz” for multiples of 5. Print “FizzBuzz” for multiples of both 3 and 5. Otherwise, print the number in ...

**Question 156. Decode String** Suppose, you are given an encoded string. A string is encoded in some kind of pattern, your task is to decode the string. Let us say, < no of times string occurs > [string ] Example Input 3[b]2[bc] Output bbbcaca Explanation Here “b” occurs 3times and “ca” occur 2 times. ...

**Question 157. Postfix to Infix Conversion** In postfix to infix conversion problem, we have given expression in postfix notation. Write a program to convert the given notation in infix notation. Infix Notation In this notation, the operators are written between the operands. It is similar to how we generally write an expression. For instance: A + ...

**Question 158. Next Permutation** In the next permutation problem we have given a word, find the lexicographically greater_permutation of it. Example input : str = "tutorialcup" output : tutorialpcu input : str = "nmhdgfecba" output : nmheabcdfg input : str = "algorithms" output : algorithsm input : str = "spoonfeed" output : Next Permutation ...

**Question 159. Longest Common Prefix using Sorting** In the Longest Common Prefix using Sorting problem we have given a set of strings, find the longest common prefix. i.e. find the prefix part that is common to all the strings. Example Input1: {“tutorialcup”, “tutorial”, “tussle”, “tumble”} Output: "tu" Input2: {"baggage", "banana", "batsmen"} Output: "ba" Input3: {"abcd"} Output: "abcd" ...

**Question 160. Backspace String Compare** In the backspace string compare problem we have given two Strings S and T, check if they are equal or not. Note that the strings contain ‘#’ which means backspace character. Examples Input S = “ab#c” T = “ad#c” Output true (as both S and T converts to “ac”) Input ...

**Question 161. Regular Expression Matching** In the Regular Expression Matching problem we have given two strings one (let’s assume it x) consists of only lower case alphabets and second (let’s assume it y) consists of lower case alphabets with two special characters i.e, “.” and “*”. The task is to find whether the second string ...

**Question 162. Reorganize String** In Reorganize String problem we have given a string containing some characters “a-z” only. Our task is to rearrange those characters such that no two same characters are adjacent to each other. Example Input apple Output pelpa Input book Output obko Input aa Output not possible Input aaab Output not ...

**Question 163. String Compression** In the String Compression problem, we have given an array a[ ] of type char. Compress it as the character and count of a particular character (if the count of character is 1 then the only character is stored in a compressed array). The length of the compressed array should ...

**Question 164. Valid Parentheses** In Valid Parentheses problem we have given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. ( ) [ ] { } ...

**Question 165. Longest Common Prefix using Trie** In the Longest Common Prefix using Trie problem we have given a set of strings, find the longest common prefix. i.e. find the prefix part that is common to all the strings. Example Input1: {“tutorialcup”, “tutorial”, “tussle”, “tumble”} Output: "tu" Input2: {"baggage", "banana", "batsmen"} Output: "ba" Input3: {"abcd"} Output: "abcd" ...

**Question 166. Count and Say** Count and Say in which we have given a number N and we need to find the Nth term of the count and say sequence. Firstly we need to understand what is count and say sequence. Firstly see some terms of the sequence: 1st term is “1”. 2nd term is ...

**Question 167. Find unique character in a string** In Find unique character in a string problem, we have given a string containing only lower case alphabets(a-z). We need to find the first non-repeating character in it and print the index. if no such character exists print -1. Input Format Only a single line containing string. Output Format Print ...

**Question 168. Integer to Roman** Integer to Roman conversion. We have given a number N and we need to print the Roman number of N. Roman numbers are represented by the use of {I, V, X, L, C, D, M} values. Let’s see some examples for good understanding. Input Format Only a single line containing ...

**Question 169. Perform String Shifts Leetcode** A shift is a process in which alphabets are incremented by 1 in their ASCII value. For the last alphabet z it starts again i.e. shift of z will be a. In perform string shifts leetcode problem we have Given a string s (lowercase characters only) and an array a[ ...

**Question 170. Check whether Strings are K Distance Apart or Not** Problem Statement Given two strings and an integer k, write a program to check whether the given strings are k distance apart or not. That is if any character is mismatched or any character is to be removed then it is known as k distance apart. Input Format The first ...

**Question 171. Check length of a String is Equal to the Number Appended at its Last** Problem Statement In the “Check length of a string is Equal to the Number Appended at its Last” problem we have given a string that is appended with a number at last. Write a program that checks whether the length of the string excluding the number is the same as ...

**Question 172. Check if all Rows of a Matrix are Circular Rotations of Each Other** Problem Statement In the “Check if all Rows of a Matrix are Circular Rotations of Each Other” problem we have given a char matrix, write a program to find whether all rows are circular rotations of each other or not. If all rows are circular rotations of each other print ...

**Question 173. Sort a String According to Another String** Problem Statement Given two input strings, a pattern and a string. We need to sort the string according to the order defined by the pattern. Pattern string has no duplicates and it has all characters of the string. Input Format The first line containing a string s which we need ...

**Question 174. Check if String Follows Order of Characters by a Pattern or not** Problem Statement In the “Check if String Follows Order of Characters by a Pattern or not” problem we have to check if characters in the given input string follow the same order as determined by characters present in the given input pattern then print “Yes” else print “No”. Input Format ...

**Question 175. Reverse String Without Temporary Variable** Problem Statement In the “Reverse String Without Temporary Variable” problem we have given a string “s”. Write a program to reverse this string without using any extra variable or space. Input Format The first line containing the given string “s”. Output Format Print the string which is reverse of the ...

**Question 176. Minimum Characters to be Added at Front to Make String Palindrome** Problem Statement In the “Minimum Characters to be Added at Front to Make String Palindrome” problem we have given a string “s”. Write a program to find the minimum characters to be added at the front to make a string palindrome. Input Format The first and only one line containing ...

**Question 177. Kth Non-repeating Character** Problem Statement In the “Kth Non-repeating Character” we have given a string “s”. Write a program to find out the kth non-repeating_character. If there are less than k character which is non-repeating in the string then print “-1”. Input Format The first and only one line containing a string “s”. ...

**Question 178. Generate all Binary Strings from Given Pattern** Problem Statement In the “Generate all Binary Strings from Given Pattern” problem we have given input string “s” consists of 0, 1, and ? (wildcard char). We need to generate all possible binary strings by replacing ? with ‘0’ and ‘1’. Input Format The first and only one line containing ...

**Question 179. Longest Common Prefix Word by Word Matching** Problem Statement In the “Longest Common Prefix using Word by Word Matching” problem, we have given N strings. Write a program to find the longest common prefix of the given strings. Input Format The first line containing an integer value N which denotes the number of strings. Next N lines ...

**Question 180. Longest Common Prefix using Character by Character Matching** Problem Statement In the “Longest Common Prefix using Character by Character Matching” problem we have given an integer value N and N strings. Write a program to find the longest common prefix of the given strings. Input Format The first line containing an integer value N which denotes the number ...

**Question 181. Permutations of a Given String Using STL** Problem Statement In the “Permutations of a Given String Using STL” problem, we have given a string “s”. Print all the permutations of the input string using STL functions. Input Format The first and only one line containing a string “s”. Output Format Print all the permutation of the given ...

**Question 182. Longest Common Prefix Using Binary Search II** Problem Statement In the “Longest Common Prefix Using Binary Search II” problem we have given an integer value N and N strings. Write a program that will print the longest common prefix of given strings. If there is no common prefix then print “-1”. Input Format The first line containing ...

**Question 183. Length of Longest valid Substring** Problem Statement In the “Length of Longest valid Substring” we have given a string that contains the opening and closing parenthesis only. Write a program that will find the longest valid parenthesis substring. Input Format The first and only one line containing a string s. Output Format The first and ...

**Question 184. Arrange given Numbers to Form the Biggest Number II** Problem Statement In the “Arrange given Numbers to Form the Biggest Number II” problem, we have given an array of positive integers. Arrange them in such a way that the arrangement will form the largest value. Input Format The first and only one line containing an integer n. Second-line containing ...

**Question 185. Check if a Linked list of Strings form a Palindrome** Problem Statement In the “Check if a Linked list of Strings form a Palindrome” problem we have given a linked list handling string data. Write a program to check whether the data forms a palindrom or not. Example ba->c->d->ca->b 1 Explanation: In the above example we can see that the ...

## Tree Questions Microsoft

**Question 186. Root to Leaf path with target sum Leetcode Solutions** A binary tree and an integer K are given. Our goal is to return whether there is a root-to-leaf path in the tree such that it’s sum is equal to the target-K. The sum of a path is the sum of all nodes that lie on it. 2 / \ ...

**Question 187. Queries for Number of Distinct Elements in a Subarray** We have given an array of integer and a number of queries and we have to find out the number of all the distinct elements we have within the given range, the query consists of two numbers left and right, this is the given range, with this given range we ...

**Question 188. Morris Traversal** Morris traversal is a method to traverse the nodes in a binary tree without using stack and recursion. Thus reducing the space complexity to linear. Inorder Traversal Example 9 7 1 6 4 5 3 1 / \ 2 ...

**Question 189. Construct Binary Tree from given Parent Array representation** The problem “Construct Binary Tree from given Parent Array representation” states that you are given an array. This input array represents a binary tree. Now you need to construct a binary tree on the basis of this input array. The array stores the index of parent node at each index. ...

**Question 190. Given a binary tree, how do you remove all the half nodes?** The problem “Given a binary tree, how do you remove all the half nodes?” states that you are given a binary tree. Now you need to remove the half nodes. A half node is defined as a node in the tree that has only a single child. Either it is ...

**Question 191. Iterative Preorder Traversal** The problem “Iterative Preorder Traversal” states that you are given a binary tree and now you need to find the preorder traversal of the tree. We are required to find the preorder traversal using iterative method and not the recursive approach. Example 5 7 9 6 1 4 3 ...

**Question 192. Write Code to Determine if Two Trees are Identical** The problem “Write Code to Determine if Two Trees are Identical” states that you are given two binary trees. find out if they are identical or not? Here, identical tree means that both the binary trees have the same node value with the same arrangement of nodes. Example Both trees ...

**Question 193. Boundary Traversal of binary tree** Problem Statement The problem “Boundary Traversal of binary tree” states that you are given a binary tree. Now you need to print the boundary view of a binary tree. Here boundary traversal means that all the nodes are shown as the boundary of the tree. The nodes are seen from ...

**Question 194. Clone a Binary Tree with Random Pointers** Problem Statement You are given a complete binary tree with some random pointers. Random pointers are referred to nodes which every node points to other than its left and right child. So, this also changes the standard structure of a node in a simple binary tree. Now the node of ...

**Question 195. Level order traversal using two Queues** Problem Statement The problem “Level order traversal using two Queues” states that you are given a binary tree, print its level order traversal line by line. Examples Input 5 11 42 7 9 8 12 23 52 3 Input 1 2 3 4 5 6 Algorithm for Level Order Traversal ...

**Question 196. Convert BST into a Min-Heap without using array** Problem Statement “Convert BST into a Min-Heap without using array” problem states that you are given a BST (binary search tree) and you need to convert it into a min-heap. The min-heap should contain all the elements in the binary search tree. The algorithm should run in linear time complexity. ...

**Question 197. Merge two BSTs with limited extra space** Problem Statement The problem “Merge two BSTs with limited extra space” states that you are given two binary search tree(BST) and you need to print the elements from both the trees in sorted order. That is in such an order that it seems that elements are from a single BST. ...

**Question 198. Binary Tree to Binary Search Tree Conversion using STL set** Problem Statement We are given a binary tree and we need to convert it into a binary search tree. The problem “Binary Tree to Binary Search Tree Conversion using STL set” asks to do conversion using STL set. We have already discussed converting the binary tree into BST but we ...

**Question 199. K’th Largest element in BST using constant extra space** Problem Statement “K’th Largest element in BST using constant extra space” states that you are given a binary search tree and you need to find the kth largest element in it. So if we arrange the elements of the binary search tree in descending order then we need to return ...

**Question 200. Vertical sum in a given binary tree** Problem Statement “Vertical sum in a given binary tree” problem states that you are given a binary tree and we need to find the sum of each vertical level. By vertical level, we mean if we draw vertical lines at a distance of 1 unit in the left and right ...

**Question 201. A program to check if a binary tree is BST or not** Problem Statement “A program to check if a binary tree is BST or not” states that you are given a binary tree and you need to check if the binary tree satisfies the properties of the binary search tree. So, the binary tree has the following properties: The left subtree ...

**Question 202. Merge Two Balanced Binary Search Trees** Problem Statement Given Two Balanced Binary Search Trees, there are n elements in the first BST and m elements in the second BST. Write an algorithm to merge two balanced binary search trees to form a third balanced Binary Search Tree with (n + m) elements. Example Input Output Pre-order ...

**Question 203. Binary Search Tree Search and Insertion** Problem Statement Write an algorithm to perform searching and insertion in Binary Search Tree. So what we are going to do is insert some of the elements from input into a binary search tree. Whenever asked to search a particular element, we’ll be searching it among the elements in BST(short ...

**Question 204. Check given array of size n can represent BST of n levels or not** Problem Statement Given an array with n elements, check given array of size n can represent BST of n levels or not. That is to check whether the binary search tree constructed using these n elements can represent a BST of n levels. Examples arr[] = {10, 8, 6, 9, ...

**Question 205. Binary Tree to Binary Search Tree Conversion** In binary tree to binary search tree conversion problem, we have given a binary tree convert it to Binary Search Tree without changing the structure of the tree. Example Input Output pre-order : 13 8 6 47 25 51 Algorithm We do not have to change the structure of the ...

**Question 206. Sorted Array to Balanced BST** In sorted array to balanced BST problem, we have given an array in sorted order, construct a Balanced Binary Search Tree from the sorted array. Examples Input arr[] = {1, 2, 3, 4, 5} Output Pre-order : 3 2 1 5 4 Input arr[] = {7, 11, 13, 20, 22, ...

**Question 207. Construct BST from its given Level Order Traversal** Given the level order traversal of a Binary Search Tree, write an algorithm to construct the Binary Search Tree or BST from ITS given level order traversal. Example Input levelOrder[] = {18, 12, 20, 8, 15, 25, 5, 9, 22, 31} Output In-order : 5 8 9 12 15 18 ...

**Question 208. BST to a Tree with Sum of all Smaller Keys** In this problem we have given a Binary Search Tree, write an algorithm to convert best to a tree with sum of all smaller keys. Example Input Output Pre-order : 19 7 1 54 34 88 Naive Approach Traverse all the nodes one by one in any traversal form, and ...

**Question 209. Find the node with minimum value in a Binary Search Tree** Given a Binary Search Tree, write an algorithm to find the node with the minimum value in a given binary search tree. Example Input Output 5 Naive Approach A simple approach is to do a tree traversal and find the node with the minimum value among all the nodes. This ...

**Question 210. Construct Binary Tree from Given Inorder and Preorder Traversals** In this problem, we have inorder and preorder of the binary tree. We need to construct a binary tree from the given Inorder and Preorder traversals. Example Input: Inorder= [D, B, E, A, F, C] Preorder= [A, B, D, E, C, F] Output: Pre-order traversal of the tree formed by ...

**Question 211. Reverse a Path in BST using Queue** In reverse a path in BST using queue problem we have given a Binary Search Tree and node, write an algorithm to reverse the path from root to the given node. Assume that the node exists in the BST. Example Input Target Node = 12 Output In-order traversal before the ...

**Question 212. Level order Traversal in Spiral Form** In this problem we have given a binary tree, print its level order traversal in a spiral form. Examples Input Output 10 30 20 40 50 80 70 60 Naive Approach for Level order Traversal in Spiral Form The idea is to do a normal level order traversal using a ...

**Question 213. Balanced Binary Tree** In the balanced binary tree problem, we have given the root of a binary tree. We have to determine whether or not it is height balance. Examples Input Output true Input Output: false Balanced Binary Tree Every node in a balanced binary tree has a difference of 1 or less ...

**Question 214. Lowest Common Ancestor** Given the root of a binary tree and two nodes n1 and n2, find the LCA(Lowest Common Ancestor) of the nodes. Example What is Lowest Common Ancestor(LCA)? The ancestors of a node n are the nodes present in the path between root and node. Consider the binary tree shown in ...

**Question 215. Segment Tree** If we have performing addition on a given range of array whose element values updated any time. Then in that type of problem, we handle using a segment tree structure. Given an array a[] with n elements and you have to answer multiple queries, each of the queries is one ...

**Question 216. Binary Search Tree** A binary search tree is a Binary tree with some rules that allows us to maintain the data in a sorted fashion. As it is a binary tree hence, a node can have at max 2 children. Structure of a Binary Search Tree node Rules for Binary tree to ...

**Question 217. Maximum Binary Tree** In this problem, we have given an array a[ ] of size n. Create the maximum binary tree from the array and return its root node. It is made from the array using the following steps : The root node of the tree should be the maximum value in the given ...

**Question 218. Binary Tree zigzag level order Traversal** Given a binary tree, print the zigzag level order traversal of its node values. (ie, from left to right, then right to left for the next level and alternate between). Example consider the binary tree given below Below is the zigzag level order traversal of the above binary tree Types ...

**Question 219. Recover Binary Search Tree** Consider a binary search tree, two nodes of the tree have been swapped, design an algorithm to recover the binary search Tree. Example Consider the binary search tree given below whose two nodes have been swapped as input. Incorrect nodes on the BST are detected(highlighted) and then swapped to obtain ...

**Question 220. Populating Next Right Pointers in Each Node** Given a Binary Tree, connect nodes that are at the same level from left to right. Structure of the Tree Node: A node of the tree contains 4 components which are data(integer value), pointers(next, left and right) of the tree node type. next pointer of a node point towards its ...

**Question 221. Level of Each node in a Tree from source node** Given a tree (an acyclic fully connected graph where constituent nodes are connected by bidirectional edges) and a source node. find the level of each node in a tree form source node. It is given that level of a node v with respect to the source is the distance between ...

**Question 222. Longest Common Prefix using Trie** In the Longest Common Prefix using Trie problem we have given a set of strings, find the longest common prefix. i.e. find the prefix part that is common to all the strings. Example Input1: {“tutorialcup”, “tutorial”, “tussle”, “tumble”} Output: "tu" Input2: {"baggage", "banana", "batsmen"} Output: "ba" Input3: {"abcd"} Output: "abcd" ...

**Question 223. Validate Binary Search Tree** Problem In Validate Binary Search Tree problem we have given the root of a tree, we have to check if it is a binary search tree or not. Example : Output: true Explanation: The given tree is a binary search tree because all elements which are left to each subtree ...

**Question 224. Path Sum** What is Path Sum Problem? In the Path Sum problem, we have given a binary tree and an integer SUM. We have to find if any path from the root to leaf has a sum equal to the SUM. Path sum is defined as the sum of all the nodes ...

**Question 225. Level Order Traversal of Binary Tree** Level Order Traversal of a given binary tree is the same as the BFS of the binary tree. Do we already know about what actually BFS is? if not then don’t need to feel bad just read the whole article and visit our previous articles for better understanding. BFS is a ...

**Question 226. Deletion in a Binary Tree** Do we already know about what actually Binary Tree is? Now in this post, we are focusing on how to delete a node whose value is given. We are sure that the value of the node which we want to delete is always present before deletion in BT. In Binary ...

## Graph Questions Microsoft

**Question 227. Find the smallest binary digit multiple of given number** Problem Statement The problem “Find the smallest binary digit multiple of given number” states that you are given a decimal number N. So find the smallest multiple of N that contains only the binary digits ‘0’ and ‘1’. Example 37 111 A detailed explanation can be found below in the ...

**Question 228. Transpose Graph** Problem Statement The problem “Transpose graph” states that you are given a graph and you need to find the transpose of the given graph. Transpose: Transpose of a directed graph produces another graph with same edge & node configurations but the direction of all the edges have been reversed. Example ...

**Question 229. BFS for Disconnected Graph** Problem Statement The problem “BFS for Disconnected Graph” states that you are given a disconnected directed graph, print the BFS traversal of the graph. Example The BFS traversal of the graph above gives: 0 1 2 5 3 4 6 Approach Breadth first Search (BFS) traversal for Disconnected Directed Graph ...

**Question 230. Evaluate Division** In evaluate division problem we have given some equations, in the form, A/B = k, where A and B are strings and k is a real number. Answer some queries, if the answer does not exist return -1. Example Input: equations: a/b = 2.0 and b/c = 3.0 queries: a/c ...

**Question 231. Graph Cloning** What is Graph Cloning? Today we have with us a reference to an undirected graph. What do we have to do? Returning a deep copy of the provided graph. Let us look at the structure: The Class Node: It consists of the data value and the neighbors associated with each ...

**Question 232. Topological Sorting** Given a directed acyclic graph, topologically sort the graph nodes. Topological Sorting Example Topological sorting of above graph is -> {1,2,3,0,5,4} Theory Topological Sorting is done for a Directed Acyclic Graph (DAG). A DAG has no cycles in it. ie, there is no such path starting from any node of ...

## Stack Questions Microsoft

**Question 233. Min Stack Leetcode Solution** Problem Statement Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) — Push element x onto stack. pop() — Removes the element on top of the stack. top() — Get the top element. getMin() — Retrieve the minimum element in the stack. ...

**Question 234. Design a stack that supports getMin() in O(1) time and O(1) extra space** Design a stack that supports getMin() in O(1) time and O(1) extra space. Thus the special stack data structure must support all the operations of the stack like – void push() int pop() bool isFull() bool isEmpty() in constant time. Add an additional operation getMin() to return the minimum value ...

**Question 235. Implement a stack using single queue** Problem Statement The problem “Implement a stack using single queue” asks us to implement a stack (LIFO) data structure using a queue (FIFO) data structure. Here LIFO means Last In First Out while FIFO means First In First Out. Example push(10) push(20) top() pop() push(30) pop() top() Top : 20 ...

**Question 236. Level order Traversal in Spiral Form** In this problem we have given a binary tree, print its level order traversal in a spiral form. Examples Input Output 10 30 20 40 50 80 70 60 Naive Approach for Level order Traversal in Spiral Form The idea is to do a normal level order traversal using a ...

**Question 237. Min Stack** In min stack problem we have to design a stack to implement the following functions efficiently, push(x) –> Push an element x to the stack pop() –> Removes the item on top of stack top() –> Return the element at top of stack getMin() –> Return the minimum element present ...

**Question 238. Queue using Stacks** In queue using a stack problem, we have to implement the following functions of a queue using the standard functions of stack data structure, Enqueue: Add an element to the end of the queue Dequeue: Remove an element from the start of the queue Example Input: Enqueue(5) Enqueue(11) Enqueue(39) Dequeue() ...

**Question 239. Next Greater Frequency Element** In the next greater frequency element problem, we have given an array a[ ] of size n containing numbers. For each number in the array print, the number to it’s right in an array with a frequency greater than that of the current number. Example Input a[] = {1, 1, ...

**Question 240. Trapping Rain Water** In Trapping Rain Water problem we have given N non-negative integers representing an elevation map and the width of each bar is 1. We have to find the amount of water that can be trapped in the above structure. Example Let’s understand that by an example For the above elevation ...

**Question 241. Decode String** Suppose, you are given an encoded string. A string is encoded in some kind of pattern, your task is to decode the string. Let us say, < no of times string occurs > [string ] Example Input 3[b]2[bc] Output bbbcaca Explanation Here “b” occurs 3times and “ca” occur 2 times. ...

**Question 242. Postfix to Infix Conversion** In postfix to infix conversion problem, we have given expression in postfix notation. Write a program to convert the given notation in infix notation. Infix Notation In this notation, the operators are written between the operands. It is similar to how we generally write an expression. For instance: A + ...

**Question 243. Binary Tree zigzag level order Traversal** Given a binary tree, print the zigzag level order traversal of its node values. (ie, from left to right, then right to left for the next level and alternate between). Example consider the binary tree given below Below is the zigzag level order traversal of the above binary tree Types ...

**Question 244. Backspace String Compare** In the backspace string compare problem we have given two Strings S and T, check if they are equal or not. Note that the strings contain ‘#’ which means backspace character. Examples Input S = “ab#c” T = “ad#c” Output true (as both S and T converts to “ac”) Input ...

**Question 245. Implement Two Stacks in an Array** Problem Statement In the “Implement Two Stacks in an Array” problem we have to implement two stacks in an array such that, if the user wants to push an element in either of two stacks then there should not be an error till the array gets full. Example Push 5 ...

**Question 246. The Celebrity Problem** Problem Statement In the celebrity problem there is a room of N people, Find the celebrity. Conditions for Celebrity is- If A is Celebrity then Everyone else in the room should know A. A shouldn’t know anyone in the room. We need to find the person who satisfies these conditions. ...

**Question 247. Next Greater Element in an Array** Problem Statement Given an array, we will find the next greater element of each element in the array. If there is no next greater element for that element then we will print -1, else we will print that element. Note: Next greater element is the element that is greater and ...

## Queue Questions Microsoft

**Question 248. Level order traversal using two Queues** Problem Statement The problem “Level order traversal using two Queues” states that you are given a binary tree, print its level order traversal line by line. Examples Input 5 11 42 7 9 8 12 23 52 3 Input 1 2 3 4 5 6 Algorithm for Level Order Traversal ...

**Question 249. Implement a stack using single queue** Problem Statement The problem “Implement a stack using single queue” asks us to implement a stack (LIFO) data structure using a queue (FIFO) data structure. Here LIFO means Last In First Out while FIFO means First In First Out. Example push(10) push(20) top() pop() push(30) pop() top() Top : 20 ...

**Question 250. Find the First Circular Tour that visits all the Petrol Pumps** Problem Statement The problem “Find the First Circular Tour that visits all the Petrol Pumps” states that there are N petrol pumps on a circular road. Given the petrol that every petrol pump has and the amount of petrol required to cover the distance between two petrol pumps. So you ...

**Question 251. Queue based approach for first non-repeating character in a stream** Problem Statement The problem “Queue based approach for first non-repeating character in a stream” states that you are given a stream containing lower case characters, find the first non-repeating character whenever a new character is added to the stream, and if there is no non-repeating character return -1. Examples aabcddbe ...

**Question 252. Implementation of Deque using circular array** Problem Statement “Implementation of Deque using circular array” asks to implement the following functions of a Deque(Doubly Ended Queue) using circular array, insertFront(x) : insert an element x at the front of Deque insertRear(x) : insert an element x at the rear of Deque deleteFront() : delete an element from ...

**Question 253. Find the node with minimum value in a Binary Search Tree** Given a Binary Search Tree, write an algorithm to find the node with the minimum value in a given binary search tree. Example Input Output 5 Naive Approach A simple approach is to do a tree traversal and find the node with the minimum value among all the nodes. This ...

**Question 254. Reverse a Path in BST using Queue** In reverse a path in BST using queue problem we have given a Binary Search Tree and node, write an algorithm to reverse the path from root to the given node. Assume that the node exists in the BST. Example Input Target Node = 12 Output In-order traversal before the ...

**Question 255. Queue using Stacks** In queue using a stack problem, we have to implement the following functions of a queue using the standard functions of stack data structure, Enqueue: Add an element to the end of the queue Dequeue: Remove an element from the start of the queue Example Input: Enqueue(5) Enqueue(11) Enqueue(39) Dequeue() ...

**Question 256. Priority Queue in C++** FIFO manner is used to implement a queue. In a queue, insertions are done at one end (rear) and deletion takes place at another end (front). Basically, the element enters first is deleted first. We implement a priority queue using c++ inbuilt functions. Characteristics of Priority Queue A priority queue ...

**Question 257. Priority Queue** A priority queue is a type of data structure which is similar to a regular queue but has a priority associated with each of its element. Higher the priority earlier the element will be served. In some cases, there are two elements with the same priority then, the element enqueued ...

**Question 258. Binary Tree zigzag level order Traversal** Given a binary tree, print the zigzag level order traversal of its node values. (ie, from left to right, then right to left for the next level and alternate between). Example consider the binary tree given below Below is the zigzag level order traversal of the above binary tree Types ...

**Question 259. Level Order Traversal of Binary Tree** Level Order Traversal of a given binary tree is the same as the BFS of the binary tree. Do we already know about what actually BFS is? if not then don’t need to feel bad just read the whole article and visit our previous articles for better understanding. BFS is a ...

## Matrix Questions Microsoft

**Question 260. Word Search Leetcode Solution** Problem Statement Given an m x n board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where “adjacent” cells are horizontally or vertically neighbouring. The same letter cell may not be used more than once. Example ...

**Question 261. Gold Mine Problem** Problem Statement The “Gold Mine problem” states that you are given a 2D grid having some non-negative coins placed in each cell of the given grid. Initially, the miner is standing at the first column but there is no restriction on the row. He can start in any row. The ...

**Question 262. Minimum time required to rot all oranges** Problem Statement The problem “Minimum time required to rot all oranges” states that you are given a 2D array, every cell has one of the three possible values 0, 1 or 2. 0 means an empty cell. 1 means a fresh orange. 2 means a rotten orange. If a rotten ...

**Question 263. Mobile Numeric Keypad Problem** Problem Statement In the mobile numeric keypad problem, we consider a numeric keypad. We need to find all number of possible numeric sequences of given length such that you are only allowed to press buttons which are top, down, left, and right of the current button. You are not allowed ...

**Question 264. Largest rectangular sub-matrix whose sum is 0** Problem Statement Find the maximum size sub-matrix in a 2D array whose sum is zero. A sub-matrix is nothing but a 2D array inside of the given 2D array. So, you have a matrix of signed integers, you need to calculate the sum of sub-matrices and find the matrix with ...

**Question 265. Matrix Chain Multiplication** In the matrix chain multiplication II problem, we have given the dimensions of matrices, find the order of their multiplication such that the number of operations involved in multiplication of all the matrices is minimized. Consider you have 3 matrices A, B, C of sizes a x b, b x ...

**Question 266. Set Matrix Zeroes** In the set matrix zeroes problem, we have given a (n X m) matrix, if an element is 0, set its entire row and column 0. Examples Input: { [1, 1, 1] [1, 0, 1] [1, 1, 1] } Output: { [1, 0, 1] [0, 0, 0] [1, 0, 1] ...

**Question 267. Unique Paths** A m x n 2D grid is given and you are standing at the topmost and leftmost cell in the grid. i.e. the cell located at (1,1). Find the number of unique paths that can be taken to reach a cell located at (m,n) from the cell located at (1,1) ...

**Question 268. Matrix Chain Multiplication using Dynamic Programming** Matrix Chain Multiplication is a method in which we find out the best way to multiply the given matrices. We all know that matrix multiplication is associative(A*B = B*A) in nature. So, we have a lot of orders in which we want to perform the multiplication. Actually, in this algorithm, ...

**Question 269. Check whether Strings are K Distance Apart or Not** Problem Statement Given two strings and an integer k, write a program to check whether the given strings are k distance apart or not. That is if any character is mismatched or any character is to be removed then it is known as k distance apart. Input Format The first ...

**Question 270. Check if all Rows of a Matrix are Circular Rotations of Each Other** Problem Statement In the “Check if all Rows of a Matrix are Circular Rotations of Each Other” problem we have given a char matrix, write a program to find whether all rows are circular rotations of each other or not. If all rows are circular rotations of each other print ...

**Question 271. Find the Row with Maximum Number of 1’s** Problem Statement In the “Find the Row with Maximum Number of 1’s” problem we have given a matrix(2D array) containing binary digits with each row sorted. Find the row which has the maximum number of 1’s. Input Format The first line containing two integers values n, m. Next, n lines ...

**Question 272. The Celebrity Problem** Problem Statement In the celebrity problem there is a room of N people, Find the celebrity. Conditions for Celebrity is- If A is Celebrity then Everyone else in the room should know A. A shouldn’t know anyone in the room. We need to find the person who satisfies these conditions. ...

## Other Questions Microsoft

**Question 273. Kth Largest Element in a Stream Leetcode Solution** Problem Statement In this problem, we have to design a class KthLargest() that initially has an integer k and an array of integers. We need to write a parameterized constructor for it when an integer k and array nums are passed as arguments. The class also has a function add(val) that adds ...

**Question 274. Remove Linked List Elements Leetcode Solution** Problem Statement In this problem, we are given a linked list with its nodes having integer values. We need to delete some nodes from the list which have value equal to val. The problem does not require to be solved in-place but we will discuss one such approach. Example List = ...

**Question 275. Minimum Moves to Equal Array Elements Leetcode Solution** Problem Statement In this problem, we are given an array of integers. Also, we are allowed to perform a certain set of operations on this array. In one operation, we can increment ” n – 1″ (all elements except any one) elements in the array by 1. We need to ...

**Question 276. Count Good Nodes in Binary Tree Leetcode Solution** Problem Statement In this problem a binary tree is given with its root. A node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. We have to return the number of good nodes in ...

**Question 277. Excel Sheet Column Number Leetcode Solution** Problem Statement In this problem we are given a column title as appear in an Excel sheet, we have to return the column number that corresponds to that column title in Excel as shown below. Example #1 "AB" 28 #2 "ZY" 701 Approach To find column number for a particular ...

**Question 278. Number of Steps to Reduce a Number to Zero Leetcode Solution** The problem Number of Steps to Reduce a Number to Zero Leetcode Solution states that given an integer. Find the minimum number of steps to convert the given integer to 0. You can perform either of the two steps, either subtract 1 or divide the integer by 2. The problem ...

**Question 279. Combinations Leetcode Solution** The problem Combinations Leetcode Solution provides us with two integers, n, and k. We are told to generate all the sequences that have k elements picked out of n elements from 1 to n. We return these sequences as an array. Let us go through a few examples to get ...

**Question 280. Jewels and Stones Leetcode Solution** The problem Jewels and Stones Leetcode Solution states that you are given two strings. One of them represents jewels and one of them represents stones. The string that contains jewels represents the characters that are jewels. We need to find the number of characters in the stones string that are ...

**Question 281. Count Odd Numbers in an Interval Range Leetcode Solution** Problem Statement In this problem, we are given two non-negative integers low and high. We have to find how many odd numbers are there in the given interval range [ low, high ]. Example low = 3, high = 7 3 Explanation: The odd numbers between 3 and 7 are ...

**Question 282. Majority Element Leetcode Solution** Problem Statement We are given an array of integers. We need to return the integer which occurs more than ⌊N / 2⌋ time in the array where ⌊ ⌋ is the floor operator. This element is called the majority element. Note that the input array always contains a majority element. ...

**Question 283. Convert a Number to Hexadecimal Leetcode Solution** The problem Convert a Number to Hexadecimal Leetcode Solution provides us with an integer. Then asks us to convert the given integer in decimal number system to hexadecimal number system. More formally, the question requires us to convert an integer given in base 10 to a base 16 representation. We ...

**Question 284. Palindrome Linked List Leetcode Solution** In the problem “Palindrome Linked List”, we have to check whether a given singly integer linked list is a palindrome or not. Example List = {1 -> 2 -> 3 -> 2 -> 1} true Explanation #1: The list is palindrome as all elements from the start and back are ...

**Question 285. Maximum Depth of Binary Tree Leetcode Solution** Problem Statement In the problem a binary tree is given and we have to find out the maximum depth of the given tree. A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 3 / ...

**Question 286. Maximum Depth of N-ary Tree Leetcode Solution** In this problem, we are given an N-ary tree, that is, a tree that allows nodes to have more than 2 children. We need to find the depth of a leaf farthest from the root of the tree. This is called maximum depth. Note that the depth of a path ...

**Question 287. Rotate List Leetcode Solution** The problem Rotate List Leetcode Solution provides us a linked list and an integer. We are told to rotate the linked list to the right by k places. So if we rotate a linked list k places to the right, in each step we take the last element from the ...

**Question 288. Pow(x, n) Leetcode Solution** The problem “Pow(x, n) Leetcode Solution” states that you are given two numbers, one of which is a floating-point number and another an integer. The integer denotes the exponent and the base is the floating-point number. We are told to find the value after evaluating the exponent over the base. ...

**Question 289. Insert into a Binary Search Tree Leetcode Solution** In this problem, we are given the root node of a Binary Search Tree containing integer values and an integer value of a node that we have to add in the Binary Search Tree and return its structure. After inserting the element into the BST, we have to print its ...

**Question 290. Merge Two Sorted Lists Leetcode Solutions** Linked lists are quite like arrays in their linear properties. We can merge two sorted arrays to form an overall sorted array. In this problem, we have to merge two sorted linked lists in place to return a new list which contains elements of both lists in a sorted fashion. Example ...

**Question 291. Permutations Leetcode Solution** The problem Permutations Leetcode Solution provides a simple sequence of integers and asks us to return a complete vector or array of all the permutations of the given sequence. So, before going into solving the problem. We should be familiar with permutations. So, a permutation is nothing but an arrangement ...

**Question 292. Two Sum Leetcode Solution** In this problem, we have to find a pair of two distinct indices in a sorted array that their values add up to a given target. We can assume that the array has only one pair of integers that add up to the target sum. Note that the array is ...

**Question 293. Count Primes Leetcode Solutions** In this problem, we are given an integer, N. The goal is to count how numbers less than N, are primes. The integer is constrained to be non-negative. Example 7 3 10 4 Explanation Primes less than 10 are 2, 3, 5 and 7. So, the count is 4. Approach(Brute ...

**Question 294. House Robber II Leetcode Solution** In the “House Robber II” problem, a robber wants to rob money from different houses. The amount of money in the houses is represented through an array. We need to find the maximum sum of money that can be made by adding the elements in a given array according to ...

**Question 295. Sqrt(x) Leetcode Solution** As the title says, we need to find the square root of a number. Let say the number is x, then Sqrt(x) is a number such that Sqrt(x) * Sqrt(x) = x. If the square root of a number is some decimal value, then we have to return the floor value of ...

**Question 296. Convert Sorted Array to Binary Search Tree Leetcode Solution** Consider we are given a sorted array of integers. The goal is to build a Binary Search Tree from this array such that the tree is height-balanced. Note that a tree is said to be height-balanced if the height difference of left and right subtrees of any node in the ...

**Question 297. Water Bottles Leetcode Solution** Problem statement In the problem ” Water Bottles” we are given two values namely” numBottle” which will store the total number of full water bottles and “numExchange” which will store the total number of empty water bottles we can exchange at a time and get a full water bottle. After ...

**Question 298. Swap Nodes in Pairs Leetcode Solutions** The goal of this problem is to swap nodes of a given linked list in pairs, that is, swapping every two adjacent nodes. If we are allowed to swap just the value of the list nodes, the problem would be trivial. So, we are not allowed to modify the node ...

**Question 299. House Robber Leetcode Solution** Problem Statement In this problem there are houses in a street and House robber has to rob these houses. But the problem is that he can’t rob more than one house successively i.e which are adjacent to each other. Given a list of non-negative integers representing the amount of money ...

**Question 300. Valid Anagrams** In the problem “Valid Anagrams” we have given two strings str1 and str2. Find out that both the strings are anagrams or not. If they are anagrams return true else return false. Example Input: str1 = “abcbac” str2 = “aabbcc” Output: true Explanation: Since str2 can be formed by rearranging ...

**Question 301. Union and Intersection of two Linked Lists** Given two linked lists, create another two linked lists to get union and intersection of the elements of existing lists. Example Input: List1: 5 → 9 → 10 → 12 → 14 List2: 3 → 5 → 9 → 14 → 21 Output: Intersection_list: 14 → 9 → 5 Union_list: ...

**Question 302. Round Robin Scheduling** The Round Robin scheduling is very much similar to FCFS. The only difference between RR and FCFS scheduling is, RR is preemptive scheduling whereas FCFS is non-preemptive scheduling. Every process is allocated to CPU in the ready queue for a single time slice. Here, a ready queue is similar to ...

**Question 303. Count ways to reach the nth stair using step 1, 2 or 3** The problem “Count ways to reach the nth stair using step 1, 2, or 3” states that you are standing on the ground. Now you need to reach the end of the staircase. So how many ways are there to reach the end if you can jump only 1, 2, ...

**Question 304. Write a function to get the intersection point of two Linked Lists** Problem Statement The problem “Write a function to get the intersection point of two Linked Lists” states that you are given two linked lists. But they are not independent linked lists. They are connected at some point. Now you need to find this point of intersection of these two lists. ...

**Question 305. Cutting a Rod** Problem Statement The problem “Cutting a Rod” states that you are given a rod of some particular length and prices for all sizes of rods which are smaller than or equal to the input length. That is we know the price for rods of length from 1 to n, considering ...

**Question 306. Check if any two intervals overlap among a given set of intervals** Problem Statement The problem “Check if any two intervals overlap among a given set of intervals” states that you are given some set of intervals. Each interval consists of two values, one is starting time and the other is ending time. The problem statement asks to check if any of ...

**Question 307. Palindrome Number** Problem Statement the problem “Palindrome Number” states that you are given an integer number. Check if it is a palindrome or not. Solve this problem without converting the given number into a string. Example 12321 true Explanation 12321 is a palindrome number because when we reverse 12321 it gives 12321 ...

**Question 308. Page Replacement Algorithms in Operating Systems** What is Page Replacement? The modern operating systems use paging for memory management and many times there is a need for page replacement. Page replacement is the process of replacing a page that is currently present in the memory with a page that is needed but is not present in ...

**Question 309. Cuckoo Hashing** Problem Statment Cuckoo Hashing is a method used to solve the problem when a collision occurs in a Hash Table. Collisions are likely of two hash values of a hash function in a table. A collision occurs when two hash values for the same key occurs in the hash function ...

**Question 310. Boolean Parenthesization Problem** Problem Statement “ Boolean Parenthesization Problem ” states that we are given a sequence of true and false, and some boolean operators( AND, OR, XOR) in between them. We need to find the number of ways to parenthesize the given sequence such that the entire sequence results in TRUE. In ...

**Question 311. Count pairs from two linked lists whose sum is equal to a given value** Problem Statement Problem “Count pairs from two linked lists whose sum is equal to a given value” state that you are given two linked lists and an integer value sum. The problem statement asked to find out how many total pair has a sum equal to the given value. Example ...

**Question 312. Word Wrap Problem** Problem Statement The word wrap problem states that given a sequence of words as input, we need to find the number of words that can be fitted in a single line at a time. So, for doing this we put breaks in the given sequence such that the printed document ...

**Question 313. Find Number of Employees Under every Employee** HashMaps are one of the most useful data structures. Find the number of employees under every employee is a problem that reminds me of the famous movie’s inception. Akin to dream in a dream. Here, we have an employee working under an employee and so on. Problem Statement So, what ...

**Question 314. Longest Increasing Subsequence** We are provided with an array of integers that is unsorted and we have to find the longest increasing subsequence. The subsequence need not be consecutive The subsequence shall be increasing Let’s understand that better by a few examples. Example Input [9, 2, 5, 3, 7, 10, 8] Output 4 ...

**Question 315. K-th Distinct Element in an Array** You are given an integer array A, print k-th distinct element in an array. The given array may contain duplicates and the output should print k-th distinct element among all unique elements in an array. If k is more than a number of distinct elements, then report it. Example Input: ...

**Question 316. Swap Nodes In Pairs** In swap nodes in pairs problem, we have given a linked list consisting of n nodes. Swap every node at even index with it’s a right adjacent node at odd index() considering index starting from 0. Example Input : 1->2->3->4->NULL Output : 2->1->4->3->NULL Input : 1->2->3->4->5->6->7->NULL Output : 2->1->4->3->6->5->7->NULL Iterative Method Algorithm Create a ...

**Question 317. Leetcode Permutations** In this leetcode problem premutation we have given an array of distinct integers, print all of its possible permutations. Examples Input arr[] = {1, 2, 3} Output 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 Input arr[] = {1, 2, ...

**Question 318. Sudoku Solver** In the sudoku solver problem we have given a partially filled (9 x 9) sudoku, write a program to complete the puzzle. Sudoku must satisfy the following properties, Every number(1-9) must appear exactly once in a row and once in a column. Every number(1-9) must appear exactly once in a ...

**Question 319. Merge K Sorted Linked Lists** Merge K sorted linked lists problem is so famous as per the interview point of view. This question asks so many times in big companies like Google, Microsoft, Amazon, etc. As the name suggests we’ve been provided with k sorted linked lists. We have to merge them together into a ...

**Question 320. Merge Two Sorted Linked Lists** In merge two sorted linked lists we have given head pointer of two linked lists, merge them such that a single linked list is obtained which has nodes with values in sorted order. return the head pointer of the merged linked list. Note: merge the linked list in-place without using ...

**Question 321. Find Median from data Stream** In Find Median from the data Stream problem, we have given that integers are being read from a data stream. Find the median of all the elements read so far starting from the first integer till the last integer. Example Input 1: stream[ ] = {3,10,5,20,7,6} Output : 3 6.5 ...

**Question 322. House Robber** The House Robber Problem states that, in a neighborhood in a city, there is a single row of n houses. A thief is planning to carry a heist in this neighborhood. He knows how much gold is concealed in each of the houses. However, in order to avoid triggering an ...

**Question 323. Word Break** Word Break is a problem that beautifully illustrates a whole new concept. We have all heard of compound words. Words made up of more than two words. Today we have a list of words and all we’ve got to do is check if all the words from the dictionary can ...

**Question 324. Merge Two Sorted Lists Leetcode** What is merge two sorted lists problem on leetcode? This is so interesting question asked so many times in compnies like Amazon, Oracle, Microsoft, etc. In this problem(Merge Two Sorted Lists Leetcode), we have given two linked lists. Both linked lists are in increasing order. Merge both linked list in ...

**Question 325. Reverse Nodes in K-Group** Problem In Reverse Nodes in K-Group problem we have given a linked list, Reverse the linked list in a group of k and return the modified list. If the nodes are not multiple of k then reverse the remaining nodes. The value of k is always smaller or equal to ...

**Question 326. LRU Cache Implementation** Least Recently Used (LRU) Cache is a type of method which is used to maintain the data such that the time required to use the data is the minimum possible. LRU algorithm used when the cache is full. We remove the least recently used data from the cache memory of ...

**Question 327. Merge Sort** What is merge sort? Merge Sort is a Recursive Procedure. It is also a divide and conquers algorithm. Now we need to know what divide and conquer algorithm is? It’s a type of procedure in which we divide the problem into subproblems and divide them until we find the shortest ...

**Question 328. Valid Sudoku** Valid Sudoku is a problem in which we have given a 9*9 Sudoku board. We need to find the given Sudoku is valid or not on the basis of the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Every of the 9 3x3 sub-boxes ...

**Question 329. Add two numbers** Add two numbers is a problem in which we have given two non-empty linked list representing a non-negative integer. The digit are store in reverse order and every node must contain only a single digit. Add the two numbers and print the result by using a linked list. Input Format ...

**Question 330. Sieve of Eratosthenes** Sieve of Eratosthenes is an algorithm in which we find out the prime numbers less than N. Here N is an integer value. This is an efficient method to find out the prime numbers to a limit. By using this we can find out the prime numbers till 10000000. Here ...

**Question 331. N queen problem** N queen problem using the concept of Backtracking. Here we place queen such that no queen under attack condition. The attack condition of the queens is if two queens are on the same column, row, and diagonal then they are under attack. Let’s see this by the below figure. Here ...

**Question 332. Serialize and Deserialize Binary Tree** We have given a binary tree containing N number of nodes where each node has some value. We need to serialize and deserialize the binary tree. Serialize The process of storing a tree in a file without disturbing its structure is called serialization. DeserializeSerialize and Deserialize Binary Tree The process ...

**Question 333. Reverse a linked list** Problem Statement The problem “reverse a linked list” states that we are given the head of the linked list. We have to reverse the linked list by changing the links between them and return the head of the reversed linked list. Example 10->20->30->40->NULL NULL<-10<-20<-30<-40 Explanation We have reversed the linked ...

**Question 334. Find Pair with Given Difference** Problem Statement In the given unsorted array, find the pair of elements in the given array with given difference n. Example Input arr[] = {120, 30, 70, 20, 5, 6}, difference(n) = 40 Output [30, 70] Explanation Here the difference of 30 and 70 is equal to the value of ...

**Question 335. Insert Node in the Sorted Linked List** Problem Statement In the “Insert Node in the Sorted Linked List” problem we have given a linked list. Insert a new node in the sorted linked list in a sorted way. After inserting a node in the sorted linked list the final linked list should be the sorted linked list. ...

**Question 336. Detect a loop in the Linked List** Problem Statement In the “Detect a loop in the Linked List” problem we have given a linked list. Find whether there is loop or not. If there is a loop in the linked list then some node in the linked list will be pointing to one of the previous nodes ...