Facebook is an American online social media and social networking service owned by Meta Platforms. Founded in 2004 by Mark Zuckerberg with fellow Harvard College students and roommates Eduardo Saverin, Andrew McCollum, Dustin Moskovitz, and Chris Hughes, its name comes from the face book directories often given to American university students. Membership was initially limited to Harvard students, gradually expanding to other North American universities and, since 2006, anyone over 13 years old. As of 2020, Facebook claimed 2.8 billion monthly active users, and ranked seventh in global internet usage. It was the most downloaded mobile app of the 2010s.

Facebook can be accessed from devices with Internet connectivity, such as personal computers, tablets and smartphones. After registering, users can create a profile revealing information about themselves. They can post text, photos and multimedia which are shared with any other users who have agreed to be their “friend” or, with different privacy settings, publicly. Users can also communicate directly with each other with Facebook Messenger, join common-interest groups, and receive notifications on the activities of their Facebook friends and pages they follow. [reference]

Categories of Questions

## Facebook Array Questions

**Question 1. Make Two Arrays Equal by Reversing Sub-arrays Leetcode Solution** The problem Make Two Arrays Equal by Reversing Sub-arrays Leetcode Solution provides us with two arrays. One of them is a target array and the other is an input array. Using the input array, we need to make the target array. We can reverse any of the sub-array in the ...

**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. Rank Transform of an Array Leetcode Solution** The problem Rank Transform of an Array Leetcode Solution provided us with an array of integers. The array or the given sequence is unsorted. We need to assign ranks to each integer in the given sequence. There are some restriction s for assigning the ranks. The ranks must start with ...

**Question 8. Find Winner on a Tic Tac Toe Game Leetcode Solution** The problem Find Winner on a Tic Tac Toe Game Leetcode Solution asks us to find out the winner of a tic tac toe game. The problem provides us with an array or vector of moves made by the players. We need to go through the moves and judge who ...

**Question 9. Minimum Time Visiting All Points Leetcode Solution** The problem Minimum Time Visiting All Points Leetcode Solution provides us with an array or vector of points on coordinate axes. The problem after providing us with the input asks us to find the minimum time to visit all the points given in the input. When you move one unit ...

**Question 10. 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 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. Contains Duplicate II Leetcode Solution** Problem Statement In this problem we are given an array of integers and we have to check if there exists any duplicate element which are at a distance of at least k to each other. i.e. the difference between the indices of those two same element should be less than ...

**Question 13. Summary Ranges Leetcode Solution** Problem Statement In Summary Ranges problem a sorted unique integer array is given. We have to make smallest sorted list of ranges that cover all numbers in array exactly once i.e. each element of array is covered by exactly one of the ranges. Each range [a,b] in the list should ...

**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. Third Maximum Number Leetcode Solution** As the title says, the goal is to find the third maximum integer in a given array of integers. Note that we need to find the distinct third maximum integer in the array. We return the maximum integer in the array when it has no distinct third maximum integer. Example ...

**Question 16. 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 17. 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 18. 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 19. 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 20. 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 21. Maximum Number of Chocolates to be Distributed Equally Among k Students** “The maximum number of chocolates to be distributed equally among k students” states that you are given n boxes that have some chocolates in it. Suppose there are k students. The task is to distribute the maximum number of chocolates among k students equally, by selecting consecutive boxes. We can ...

**Question 22. Count and Toggle Queries on a Binary Array** An array of size n has been given as an input value. The problem “Count and Toggle Queries on a Binary Array” asks to perform some of the queries which are given below, queries can vary in a random manner. The queries are ⇒ Toggle query ⇒ toggle(starting, ending), this ...

**Question 23. 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 24. Monotonic Array LeetCode Solution** Problem statement In the problem “Monotonic Array” we are given an array. Our task is to check if the array is a monotonic array or not. A monotonic array is an array where elements are either sorted in increasing order or in decreasing order. If the array is sorted in ...

**Question 25. Check if Array Contains Contiguous Integers With Duplicates Allowed** You are given an array of integers which can contain duplicate elements as well. The problem statement asks to find out if it is a set of contiguous integers, print “Yes” if it is, print “No” if it is not. Example Sample Input: [2, 3, 4, 1, 7, 9] Sample ...

**Question 26. 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 27. Sum of f(a[i], a[j]) over all pairs in an array of n integers** The problem statement asks to find out the Sum of f(a[i], a[j]) over all pairs in an array of n integers in such a way that 1 < = i < j < = n considering that we are provided an array of integers. Example arr[] = {1, 2, 3, ...

**Question 28. Count of index pairs with equal elements in an array** Suppose, we have given an integer array. The problem “Count of index pairs with equal elements in an array” asks to find out the no of pair of indices (i,j) in such a way that arr[i]=arr[j] and i is not equal to j. Example arr[] = {2,3,1,2,3,1,4} 3 Explanation Pairs ...

**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. 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 32. Painting Fence Algorithm** Problem Statement The “Painting Fence Algorithm” states that you are given a fence having some posts (some wooden pieces or some other pieces) and some colors. Find out the number of ways to paint the fence such that at most only 2 adjacent fences have the same color. Since this ...

**Question 33. 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 34. 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 35. Remove duplicates from sorted array** Problem Statement “Remove duplicates from sorted array” states that you are given a sorted array of size N. You need to remove the duplicate elements from the array. Print the array containing unique elements after the removal of duplicate elements. Example a [] = {1, 1, 1, 1} {1} Explanation: ...

**Question 36. Contiguous Array Leetcode** Problem Statement “Contiguous Array Leetcode” problem states that you are given an array a[ ] of size n consists of 1’s and 0’s only. Find the longest subarray in which the number of 1’s is equal to the number of 0’s. Example a[ ] = {1, 0, 1, 1, 1, ...

**Question 37. K maximum sums of overlapping contiguous sub-arrays** Problem Statement The problem “K maximum sums of overlapping contiguous sub-arrays” states that you are given an array of integers. Find the maximum sum of k-subarrays such that their sum is maximum. These k-subarrays might be overlapping. So, we need to find k-subarrays such that their sum is maximum among ...

**Question 38. Given two unsorted arrays find all pairs whose sum is x** Problem Statement Given two unsorted arrays, find all pairs whose sum is x problem states that you are given two arrays of integers that are unsorted and a value called sum. The problem statement asks to find out the total number of pairs and print all those pairs that add ...

**Question 39. 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 40. 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 41. 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 42. Maximal Square** In the maximal square problem we have given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s, and return its area. Example Input: 1 0 1 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 1 0 ...

**Question 43. 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 44. 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 45. 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 46. 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 47. 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 48. 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 49. 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 50. 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 51. Toeplitz Matrix** Given a 2-D matrix of size (m x n), check whether the matrix is Toeplitz or not. A Toeplitz matrix is a matrix in which the elements on the same diagonal from top left to bottom left are the same for all the diagonals. Examples Input 1 2 3 4 ...

**Question 52. 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 53. 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 54. Maximum Sum of 3 Non-Overlapping Subarrays** In the maximum sum of 3 non-overlapping subarrays problem we have given an array nums of positive integers, find three non-overlapping subarrays of length k with a maximum sum, and return their starting indices. Example Input: nums[] = {1, 2, 1, 2, 6, 7, 5, 1} k = 2 Output: ...

**Question 55. Reservoir Sampling** Reservoir Sampling is a technique of selecting k reservoir items randomly from a given list of n items, where n is very large. For example, search lists in Google, YouTube etc. Naive Approach for Reservoir Sampling Build a reservoir array of size k, randomly select items from the given list. ...

**Question 56. 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 57. 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 58. 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 59. 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 60. Max Area of Island** Problem Description: Given a 2D matrix, the matrix has only 0(representing water) and 1(representing land) as entries. An island in the matrix is formed by grouping all the adjacent 1’s connected 4-directionally(horizontal and vertical). Find the maximum area of the island in the matrix. Assume that all four edges of ...

**Question 61. 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 62. 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 63. 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 64. 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 65. Find Peak Element** Let’s understand Find Peak Element problem. Today we have with us an array that needs its peak element. Now, you must be wondering as to what do I mean by the peak element? The peak element is one which is greater than all its neighbours. Example: Given an array of ...

**Question 66. K-th Smallest Element in a Sorted Matrix** In K-th Smallest Element in a Sorted Matrix problem, we have given an n x n matrix, where every row and column is sorted in non-decreasing order. Find the kth smallest element in the given 2D array. Example Input 1: k = 3 and matrix = 11, 21, 31, 41 ...

**Question 67. 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 68. 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 69. 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 70. Partition Equal Subset Sum** Partition Equal Subset Sum is a problem in which we have given an array of positive numbers. We have to find out that can we divide it into two subsets such that the sum of elements in both sets is the same. Here it’s not necessary that the number of ...

**Question 71. Sort Colors** Sort colors is a problem in which we have to given an array containing N objects. Each box is painted with a single color which can be red, blue, and white. We have N objects which are already painted. We have to sort the array such that the same color ...

**Question 72. Container with Most Water** Problem description : you are given n integers (y0, y1, y2 … yn-1) at n indices (i = 0,1,2 … n-1). Integer at i-th index is yi. Now, you draw n lines on a cartesian plane each connecting points (i, yi) and (i, 0). Find the maximum volume of water ...

**Question 73. 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 74. Coin Change Problem** Coin Change Problem – Given some coins of different values c1, c2, … , cs (For instance: 1,4,7….). We need an amount n. Use these given coins to form the amount n. You can use a coin as many times as required. Find the total number of ways in which ...

**Question 75. Multiplication of Two Matrices** Problem Statement In the “Multiplication of Two Matrices” problem we have given two matrices. We have to multiply these matrices and print the result or final matrix. Here, the necessary and sufficient condition is the number of columns in A should be equal to the number of rows in matrix ...

**Question 76. 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 77. 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 78. 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 79. 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 80. 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 81. 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 82. 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 83. 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 84. 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 85. Largest Subarray with Equal Number of 0’s and 1’s** Problem Statement In the “Largest Subarray with Equal Number of 0’s and 1’s” problem, we have given an array a[] containing only 0 and 1. Find the largest subarray with an equal number of 0’s and 1’s and will print the start index and end index of the largest subarray. ...

**Question 86. 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 87. Increasing Subsequence of Length three with Maximum Product** Problem Statement In the “Increasing Subsequence of Length three with Maximum Product” problem, we have given an array of positive integers. Find the subsequence of length 3 with the maximum product. Subsequence should be increasing. Input Format The first and only one line containing an integer N denoting the size ...

**Question 88. 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 89. 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 90. Rearrange Positive and Negative Numbers Alternatively in Array** Problem Statement In the “Rearrange Positive and Negative Numbers Alternatively in Array” problem we have given an array a[]. This array contains positive and negative integers. Rearrange the array in such a way that positive and negative are placed alternatively. Here, the number of positive and negative elements need not ...

**Question 91. 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 92. Maximum Circular Subarray Sum** Problem Statement In the maximum circular subarray sum problem, we have given an array of integers arranged in a circle, find the maximum sum of consecutive numbers in the circular array. Example Input arr[] = {13, -17, 11, 9, -4, 12, -1} Output 40 Explanation Here, sum = 11 + ...

**Question 93. 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 94. 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 95. Find a Sorted Subsequence of size 3** Problem Statement In the given unsorted array of integers. We need to find a sorted subsequence of size 3. Let three elements be array[i], array[j], array[k] then, array[i] < array[j] < array[k] for i< j < k. If there are multiple triplets found in the array then print any one ...

**Question 96. 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 97. 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 98. Rearrange given Array in Maximum Minimum Form** Problem Statement In the “Rearrange given Array in Maximum Minimum Form” problem, we have given a sorted array containing N elements. Rearrange the given sorted array of positive integers, such that alternative elements are ith max and ith min. See below for a better understanding of rearrangement of elements- Array[0] ...

**Question 99. 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 100. 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 101. 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 102. 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 103. 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 104. 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 105. 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 106. 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 107. 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 108. 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 109. 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 110. Maximum Sum of Non Consecutive Elements** Problem Statement In the “Maximum Sum of Non Consecutive Elements” given array, you need to find the maximum sum of non-consecutive elements. You can not add immediate neighbor numbers. For example [1,3,5,6,7,8,] here 1, 3 are adjacent so we can’t add them, and 6, 8 are not adjacent so we ...

**Question 111. 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 112. 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 113. 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 114. 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 115. 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 116. 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 ...

## Facebook String Questions

**Question 117. Check If Two String Arrays are Equivalent Leetcode Solution** The problem Check If Two String Arrays are Equivalent Leetcode Solution provides us two arrays of strings. Then we are told to check if these two string arrays are equivalent. The equivalence here refers to the fact that if the strings in the arrays are concatenated. Then after concatenation, both ...

**Question 118. 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 119. 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 120. 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 121. 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 122. Reverse Vowels of a String Leetcode Solution** Problem Statement In this problem a string is given and we have to reverse only the vowels of this string. Example "hello" "holle" Explanation: before reversing : “hello” after reversing : “holle” "leetcode" "leotcede" Explanation: Approach 1 (Using Stack) We just have to reverse the vowels present in input ...

**Question 123. 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 124. 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 125. 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 126. 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 127. 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 128. Check if Array Contains Contiguous Integers With Duplicates Allowed** You are given an array of integers which can contain duplicate elements as well. The problem statement asks to find out if it is a set of contiguous integers, print “Yes” if it is, print “No” if it is not. Example Sample Input: [2, 3, 4, 1, 7, 9] Sample ...

**Question 129. Longest Repeated Subsequence** The problem “Longest Repeated Subsequence” states that you are given a string as an input. Find out the longest repeated subsequence, that is the subsequence that exists twice in the string. Example aeafbdfdg 3 (afd) Approach The problem asks us to find out the longest repeated subsequence in the string. ...

**Question 130. Check for Palindrome after every character replacement Query** The problem “Check for Palindrome after every character replacement Query” states that suppose you are given a String and no. of Queries, each query has two integer input values as i1 and i2 and one character input called ‘ch’. The problem statement asks to change the values at i1 and ...

**Question 131. 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 132. 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 133. 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 134. 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 135. 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 136. 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 137. Valid Parenthesis String** In the valid parenthesis string problem we have given a string containing ‘(‘, ‘)‘ and ‘*‘, check if the string is balanced if ‘*‘ can be replaced with ‘(‘, ‘)‘ or an empty string. Examples Input “()” Output true Input “*)” Output true Input “(*))” Output true Naive Approach for ...

**Question 138. 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 139. Find Maximum Depth of Nested Parenthesis in a String** Given a string s. Write the code to print the maximum depth of nested parenthesis in the given string. Example Input : s = “( a(b) (c) (d(e(f)g)h) I (j(k)l)m)” Output : 4 Input : s = “( p((q)) ((s)t) )” Output : 3 Using Stack Algorithm Initialize a string s of length ...

**Question 140. 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 141. 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 142. Longest Common Subsequence** You are given two strings str1 and str2, find out the length of the longest common subsequence. Subsequence: a subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. For ex ‘tticp‘ is the subsequence ...

**Question 143. 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 144. 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 145. 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 146. 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 147. 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 148. 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 149. 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 150. Valid Number** In the Valid Number problem we have given a string, check if it can be interpreted into a valid decimal number. It is to be noted that, for a given string to be interpreted as a valid decimal number. It should contain the following characters: Numbers 0-9 Exponent – “e” ...

**Question 151. 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 152. 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 153. Isomorphic Strings** Isomorphic Strings – Given two strings we need to check if for every occurrence of a character in string1 there is a unique mapping with characters in string2. In short, check, if there is one to one mapping or not. Example Input str1 = “aab” str2 = “xxy” Output True ...

**Question 154. 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 155. 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 156. Print all Palindromic Partitions of a String** Problem Statement In the “Print all Palindromic Partitions of a String” problem we have given a string “s”. Write a program to print all possible palindromic partitioning of s. A palindrome is a word, number, phrase, or another sequence of characters that reads the same backward as forward, such as ...

**Question 157. 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 158. 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 159. 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 160. 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 161. 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 162. Palindrome Permutations of a String** Problem Statement In the “Palindrome Permutations of a String” problem, we have given an input string “s”. Print all the possible palindromes that can be generated using the characters of the string. Input Format The first and only one line containing a string “s”. Output Format Print all the possible ...

**Question 163. 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 164. Smallest window in a string containing all characters of another string** Find the shortest substring in a given string that contains all the characters of a given word or Find the Smallest window in a string containing all characters of another string Given two strings s and t, write a function that will find the minimum window in s which will ...

**Question 165. 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 166. 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 ...

## Facebook Tree Questions

**Question 167. 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 168. 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 169. Red-Black Tree Introduction** Red Black Tree is a self-balancing binary tree. In this tree, every node is either a red node or a black node. In this Red-black Tree Introduction, we will try to cover all of its basic properties. Properties of Red-Black Tree Every node is represented as either red or black. ...

**Question 170. Check if all levels of two Binary Tree are anagrams or not** Problem Statement The problem “Check if all levels of two Binary Tree are anagrams or not” says that you are given two Binary Trees, check if all the levels of the two trees are anagrams or not. Examples Input true Input false Algorithm to Check if all levels of two ...

**Question 171. Sorted Linked List to Balanced BST** In sorted linked list to balanced BST problem, we have given a singly Linked list in sorted order, construct a Balanced Binary Tree from the singly Linked List. Examples Input 1 -> 2 -> 3 -> 4 -> 5 Output Pre-order : 3 2 1 5 4 Input 7 -> ...

**Question 172. Transform a BST to Greater sum Tree** In transform a BST to greater sum tree Given a Binary Search Tree write an algorithm to convert it to a greater sum tree, that is, transform each node to contain the sum of all the elements greater than it. Example Input Output Pre-order : 69 81 87 34 54 ...

**Question 173. Convert a BST to a Binary Tree such that sum of all greater keys is added to every key** Given a Binary Search Tree, write an algorithm to Convert a BST to a Binary Tree such that the sum of all greater keys is added to every key. Example Input Output Pre-order : 81 87 88 54 69 34 Naive Approach The idea is very simple, traverse all the ...

**Question 174. 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 175. Kth Smallest Element in a BST** In this problem, we have given a BST and a number k, find the kth smallest element in a BST. Examples Input tree[] = {5, 3, 6, 2, 4, null, null, 1} k = 3 Output 3 Input tree[] = {3, 1, 4, null, 2} k = 1 Output 1 ...

**Question 176. 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 177. Averages of Levels in Binary Tree** In averages of levels in binary tree problem we have given a binary tree, print the averages of all the nodes of every level in the tree. Example Input: Output: {10.0, 25.0, 45.0, 70.0} Explanation: First Level : Average = (10) / 1 = 10.0 Second Level : Average = ...

**Question 178. Lowest Common Ancestor in Binary Search Tree** Given the root of a binary search tree and two nodes n1 and n2, find the LCA(Lowest Common Ancestor) of the nodes in a given binary search tree. Example Naive Approach for Lowest Common Ancestor in Binary Search Tree Find the LCA(n1, n2) using the optimal approach to find LCA ...

**Question 179. 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 180. Symmetric Tree** In Symmetric Tree problem we have given a binary tree, check whether it is a mirror of itself. A tree is said to be a mirror image of itself if there exists an axis of symmetry through a root node that divides the tree into two same halves. Example Types ...

**Question 181. 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 182. Convert Sorted List to Binary Search Tree** Problem Given a linked list. The elements of the linked list are in increasing order. Convert the given linked list into a highly balanced binary search tree. A highly balanced binary search tree is a binary search tree in which the difference between the depth of two subtrees of any ...

**Question 183. 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 184. 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 185. 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 ...

## Facebook Graph Questions

**Question 186. Bellman Ford Algorithm** Bellman Ford Algorithm is used for Finding the shortest path from the source vertex to all the vertices. Given a graph with a source vertex and weights of edges that may be negative or positive. Now, the reader might say: We have Dijkstra already. Why bother ourselves with another algorithm? Let ...

**Question 187. 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 188. Max Area of Island** Problem Description: Given a 2D matrix, the matrix has only 0(representing water) and 1(representing land) as entries. An island in the matrix is formed by grouping all the adjacent 1’s connected 4-directionally(horizontal and vertical). Find the maximum area of the island in the matrix. Assume that all four edges of ...

**Question 189. 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 190. Minimum Height Trees** In the Minimum Height Trees problem, we have given an undirected graph which is tree in nature (acyclic and fully connected graph). Find out those vertices (or vertex) in the graph that when taken as root, will give tree with minimum height. Height of Tree: Height of the tree rooted ...

## Facebook Stack Questions

**Question 191. Find Maximum Depth of Nested Parenthesis in a String** Given a string s. Write the code to print the maximum depth of nested parenthesis in the given string. Example Input : s = “( a(b) (c) (d(e(f)g)h) I (j(k)l)m)” Output : 4 Input : s = “( p((q)) ((s)t) )” Output : 3 Using Stack Algorithm Initialize a string s of length ...

**Question 192. 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 193. 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 194. 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 195. 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 196. 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 ...

## Facebook Queue Questions

**Question 197. Check if all levels of two Binary Tree are anagrams or not** Problem Statement The problem “Check if all levels of two Binary Tree are anagrams or not” says that you are given two Binary Trees, check if all the levels of the two trees are anagrams or not. Examples Input true Input false Algorithm to Check if all levels of two ...

**Question 198. Queue Reconstruction by Height** Problem Description of Queue Reconstruction by Height Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person ...

**Question 199. 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 ...

## Facebook Matrix Questions

**Question 200. 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 201. Number of palindromic paths in a matrix** Problem Statement We are given a two-dimensional matrix containing lowercase English alphabets, we need to count the number of palindromic paths in it. A palindromic path is nothing but a path following palindromic property. A word which when reversed remains the same as the initial word is said to be ...

**Question 202. 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 203. Maximal Square** In the maximal square problem we have given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s, and return its area. Example Input: 1 0 1 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 1 0 ...

**Question 204. Toeplitz Matrix** Given a 2-D matrix of size (m x n), check whether the matrix is Toeplitz or not. A Toeplitz matrix is a matrix in which the elements on the same diagonal from top left to bottom left are the same for all the diagonals. Examples Input 1 2 3 4 ...

**Question 205. 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 206. Flood Fill LeetCode** In Flood Fill problem we have given a 2D array a[ ][ ] representing an image of size mxn with each value representing the color of the pixel at that co-ordinate. Also given the location or coordinates of a pixel and a color. Replace the color at a given location ...

**Question 207. Max Area of Island** Problem Description: Given a 2D matrix, the matrix has only 0(representing water) and 1(representing land) as entries. An island in the matrix is formed by grouping all the adjacent 1’s connected 4-directionally(horizontal and vertical). Find the maximum area of the island in the matrix. Assume that all four edges of ...

**Question 208. 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 209. K-th Smallest Element in a Sorted Matrix** In K-th Smallest Element in a Sorted Matrix problem, we have given an n x n matrix, where every row and column is sorted in non-decreasing order. Find the kth smallest element in the given 2D array. Example Input 1: k = 3 and matrix = 11, 21, 31, 41 ...

**Question 210. Multiplication of Two Matrices** Problem Statement In the “Multiplication of Two Matrices” problem we have given two matrices. We have to multiply these matrices and print the result or final matrix. Here, the necessary and sufficient condition is the number of columns in A should be equal to the number of rows in matrix ...

**Question 211. 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 212. 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. ...

## Facebook Other Questions

**Question 213. 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 214. 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 215. Hamming Distance Leetcode Solution** Problem Statement In this problem, we are given two integers, A and B, and the goal is to find the hamming distance between the given integers. The integers are greater that/equal to 0 and less than 231 Example First Integer = 5 , Second Integer = 2 3 First Integer ...

**Question 216. Moving Stones Until Consecutive Leetcode Solution** Problem Statement In this problem, we are given three stones at positions a, b and c. We have to make them consecutive by performing the following step one or more times. In each step, We will pick a left stone or a right stone and put somewhere in the between ...

**Question 217. 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 218. Intersection of Two Arrays II Leetcode Solution** Problem Statement In this problem two arrays are given and we have to find out the intersection of this two arrays and return the resultant array. Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Example ...

**Question 219. 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 220. 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 221. 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 222. 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 223. 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 224. N-th Tribonacci Number Leetcode Solution** Problem statement In the problem ” N-th Tribonacci Number” we are given a number n. Our task is to find out the N-th tribonacci number. The zeroth tribonacci number is 0. The first tribonacci number is 1. The second tribonacci number is 1. N-th tribonacci number is summation of (N-1- ...

**Question 225. 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 226. 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 227. 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 228. 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 229. 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 230. Minimum Depth of Binary Tree Leetcode Solution** In this problem, we need to find the length of the shortest path from the root to any leaf in a given binary tree. Note that the “length of the path” here means the number of nodes from the root node to the leaf node. This length is called Minimum ...

**Question 231. 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 232. 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 233. Shuffle String Leetcode Solution** Problem statement In the problem ” Shuffle String” we are given a String and an array. The array contains the new indices of the character of the string. So array[i] represents a new position of character at ith position of the string. In “Shuffle String” we need to shuffle the ...

**Question 234. Sequences of given length where every element is more than or equal to twice of previous** The problem “Sequences of given length where every element is more than or equal to twice of previous” provides us with two integers m and n. Here m is the largest number that can exist in the sequence and n is the number of elements that must be present in the ...

**Question 235. Koko Eating Bananas Leetcode Solution** Problem statement In the problem ” Koko Eating Bananas” we are given an array of size n which contains the number of bananas in each pile. In one hour Koko can eat at most K bananas. If the pile contains less than K bananas in that case if Koko finishes ...

**Question 236. How to print maximum number of A’s using given four keys** Problem Statement How to print maximum number of A’s using given four keys, this problem states that you have the option to choose which key to press. The keys perform the following tasks: Key1 – Prints ‘A’ on screen Key2 – Select the whole screen. Key3 – Copy the selected ...

**Question 237. Data Structure Designing** Listening to Data Structure Designing, A lot of people might want to run away looking at the title itself. Those who know me know that I am not leaving until I explain the concept entirely. Embark with me on a journey to learn a problem and a few ideas on ...

**Question 238. 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 239. 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 240. Intersection of Two Arrays** In intersection of two arrays problem, we have given two arrays, we need to print their intersection(common elements). Example Input arr1[] = {1, 2, 2, 1} arr2[] = {2, 2} Output {2, 2} Input arr1 = {4, 9, 5} arr2 = {9, 4, 9, 8, 4} Output {4, 9} Algorithm ...

**Question 241. 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 242. Target Sum** “Target Sum” is a special problem for all the DPHolics I have with me today. There ain’t no need to worry I am going to abandon the rest of my lovely readers. We all have gone through the classic KnapSack problem where we try to find the maximum number of ...

**Question 243. 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 244. 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 245. 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 246. Sliding Window Maximum** In Sliding Window Maximum problem we have given an array nums, for each contiguous window of size k, find the maximum element in the window. Example Input nums[] = {1,3,-1,-3,5,3,6,7} k = 3 Output {3,3,5,5,6,7} Explanation Naive Approach for Sliding Window Maximum For every contiguous window of size k, traverse ...

**Question 247. 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 248. Hamming Distance** What is Hamming Distance? Hamming distance is Technically defined as the number of bits in the same position that differs in two numbers. Let us delve into a new way of finding the distance between two numbers. Example Input To find the hamming distance between 4 and 14 4 and ...

**Question 249. First Bad Version** We all have heard the saying “Bad Apple Ruins The Bunch”.First Bad Version is a problem that beautifully illustrates the same. Today we have a problem which is First Bad Version. One of the interns has made an nth bad commit due to which commits from n+1 have all been ...

**Question 250. Number Of 1 bits** We have all heard of the Hamming Weight of a binary number. Hamming weight is the number of set bits/1s in a binary number. In this problem Number Of 1 bits we have to find the hamming weight of the given number. Examples Number = 3 Binary representation = 011 ...

**Question 251. 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 252. 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 253. 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 254. 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 255. Palindrome Partitioning** Palindrome Partitioning is a DP problem. In this problem, Given a string S. Partition S such that every substring of the partition is a palindrome. We need to print the minimum cuts needed for a palindrome partitioning of S. Input Format Only a single line containing string S. Output Format ...

**Question 256. 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 257. 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 258. Alien Dictionary** Alien Dictionary is a type of problem in which we have N-words and they are sorted in alien dictionary order. We need to find the order of the characters. The alien language is also used the lowercase letters but the order of the letters is different. Let’s see how we ...

**Question 259. 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 260. 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 ...