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 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]
You can practice below Facebook Interview Questions for the interview. We have collected past Facebook Interview Questions for your reference.
Categories of Questions
Facebook Array Questions
Question 1. Monotonic Array Leetcode Solution Problem Statement: The Monotonic Array Leetcode Solution – Given an array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j]. Given an integer array nums, return true if the given ...
Question 2. Maximum Size Subarray Sum Equals k Leetcode Solution Problem Statement: The Maximum Size Subarray Sum Equals k Leetcode Solution – Given an integer array nums and integer k, return the maximum length of a subarray that sums to k. If there is not one, return 0 instead. Example: Input: nums = [1,-1,5,-2,3], k = 3 Output: 4 Explanation: The ...
Question 3. H-Index Leetcode Solution Problem Statement: H-Index Leetcode solution says that – Given an array of integers “citations” where citations[i] is the number of citations a researcher received for their ith paper, return researcher’s H-Index. If several H-Index values are present, return the maximum among them. Definition of H-Index: A scientist has an index ...
Question 4. Continuous Subarray Sum LeetCode Solution Problem Statement Continuous Subarray Sum LeetCode Solution – Given an integer array nums and an integer k, return true if nums has a continuous subarray of the size of at least two whose elements sum up to a multiple of k, or false otherwise. An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a ...
Question 5. Top K Frequent Elements LeetCode Solution Problem Statement Top K Frequent Elements LeetCode Solution Says that – Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] ...
Question 6. Shifting Letters LeetCode Solution Problem Statement Shifting Letters says that we have given a string s and an array shifts. Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times. We have to return the final string after all shifts are applied. Example 1: Input: s = "abc", shifts ...
Question 7. Divide Chocolate LeetCode Solution Problem Statement The Divide Chocolate LeetCode solution says the chocolate bar is represented by a list of non-zero integers. The sum of a contiguous subarray stands for the sweetness of the chocolate piece represented by this subarray. Here the task is to find the maximum possible minimum sum of all ...
Question 8. Maximum Population Year LeetCode Solution Problem Statement Maximum Population Year LeetCode Solution says that – You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith a person is counted ...
Question 9. Maximum Population Year LeetCode Solution Problem Statement: Maximum Population Year Leetcode Solution says that – You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year? The ith person is counted in the year x‘s population if x is ...
Question 10. Best Meeting Point LeetCode Solution Problem Statement: Best Meeting Point Leetcode Solution says – Given a m x n binary grid grid where each 1 marks the home of one friend, return the minimal total travel distance. The total travel distance is the sum of the distances between the houses of the friends and the meeting point. The distance is calculated using Manhattan Distance, ...
Question 11. Minimum Path Sum Leetcode Solution Problem Statement The Minimum Path Sum LeetCode Solution – “Minimum Path Sum” says that given a n x m grid consisting of non-negative integers and we need to find a path from top-left to bottom right, which minimizes the sum of all numbers along the path. We can only move ...
Question 12. Number of Subsequences That Satisfy the Given Sum Condition LeetCode solution Problem Statement Number of Subsequences That Satisfy the Given Sum Condition LeetCode solution – says that Given an array of integers nums and an integer target. Return the number of non-empty subsequences nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too ...
Question 13. Insert Delete GetRandom O(1) Leetcode Solution Problem Statement The Insert Delete GetRandom O(1) LeetCode Solution – “Insert Delete GetRandom O(1)” asks you to implement these four functions in O(1) time complexity. insert(val): Insert the val into the randomized set and return true if the element is initially absent in the set. It returns false when the ...
Question 14. Daily Temperatures Leetcode Solution Problem Statement The Daily Temperatures Leetcode Solution: states that given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead. ...
Question 15. Remove Duplicates from Sorted Array II Leetcode Solution Problem Statement : Given an integer array of nums sorted in non-decreasing order, remove some duplicates in place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have ...
Question 16. K Closest Points to Origin Leetcode Solution Problem Statement The K Closest Points to Origin LeetCode Solution – “K Closest Points to Origin” states that given an array of points, x coordinates and y coordinates represent the coordinates on XY Plane. We need to find k closest points to the origin. Note that the distance between two ...
Question 17. Next Permutation Leetcode Solution Problem Statement The Next Permutation LeetCode Solution – “Next Permutation” states that given an array of integers which is a permutation of first n natural numbers. We need to find the next lexicographically smallest permutation of the given array. The replacement must be in-place and use only constant extra space. ...
Question 18. Trapping Rain Water Leetcode Solution Problem Statement The Trapping Rain Water LeetCode Solution – “Trapping Rain Water” states that given an array of heights which represents an elevation map where the width of each bar is 1. We need to find the amount of water trapped after rain. Example: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: Check ...
Question 19. Sort Array by Increasing Frequency Leetcode Solution Problem Statement The Sort Array by Increasing Frequency LeetCode Solution – “Sort Array by Increasing Frequency” states that you’re given an array of integers, sort the array in increasing order based on the frequency of the values. Two or more values have the same frequency, we need to sort them ...
Question 20. Partition to K Equal Sum Subsets Leetcode Solution Problem Statement The Partition to K Equal Sum Subsets LeetCode Solution – “Partition to K Equal Sum Subsets” states that you’re given the integer array nums and an integer k, return true if it is possible to have k non-empty subsets whose sums are all equal. Example: Input: nums = [4,3,2,3,5,2,1], k = 4 Output: ...
Question 21. Coin Change 2 Leetcode Solution Problem Statement The Coin Change 2 LeetCode Solution – “Coin Change 2” states that given an array of distinct integers coins and an integer amount, representing a total amount of money. We need to return the count of the total number of different possible combinations that sum to the amount. ...
Question 22. Frog Jump Leetcode Solution Problem Statement The Frog Jump LeetCode Solution – “Frog Jump” states that given the list of stones (positions) sorted in ascending order, determine if the frog can cross the river by landing on the last stone (last index of the array). Initially, the frog is on the first stone and ...
Question 23. Build Array From Permutation Leetcode Solution Problem Statement The Build Array From Permutation LeetCode Solution – “Build Array From Permutation” states that given zero-based permutation nums, we have to build an array of the same length where ans[i] = nums[nums[i]] for each i in range [0,nums.length-1]. A zero-based permutation nums is an array of distinct integers from 0 ...
Question 24. Minimum Cost For Tickets Leetcode Solution Problem Statement The Minimum Cost For Tickets LeetCode Solution – “Minimum Cost For Tickets” asks you to find the minimum number of dollars you need to travel every day in the given list of days. You will be given an integer array of days. Each day is an integer from ...
Question 25. Unique Paths II Leetcode Solution Problem Statement The Unique Paths II LeetCode Solution – “Unique Paths II” states that given the m x n grid where a robot starts from the top left corner of the grid. We need to find the total number of ways to reach the bottom right corner of the grid. ...
Question 26. Search a 2D Matrix II Leetcode Solution Problem Statement The Search a 2D Matrix II LeetCode Solution – “Search a 2D Matrix II”asks you to find an efficient algorithm that searches for a value target in an m x n integer matrix matrix. Integers in each row, as well as column, are sorted in ascending order. Example: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 Output: true ...
Question 27. Moving Average from Data Stream Leetcode Solution Problem Statement The Moving Average from Data Stream LeetCode Solution – “Moving Average from Data Stream” states that given a stream of integers and a window size k. We need to calculate the moving average of all the integers in the sliding window. If the number of elements in the ...
Question 28. Set Matrix Zeroes Leetcode Solution Problem Statement The Set Matrix Zeroes LeetCode Solution – “Set Matrix Zeroes” states that you’re given an m x n integer matrix matrix.We need to modify the input matrix such that if any cell contains the element 0, then set its entire row and column to 0‘s. You must do it in ...
Question 29. Missing Number Leetcode Solution Problem Statement The Missing Number LeetCode Solution – “Missing Number” states that given an array of size n containing n distinct numbers between [0,n]. We need to return the number which is missing in the range. Example: Input: nums = [3,0,1] Output: 2 Explanation: We can easily observe that all the ...
Question 30. 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 31. 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 32. 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 33. 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 34. 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 35. 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 36. 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 37. 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 38. 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 39. 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 40. 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 41. 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 42. 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 43. 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 44. 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 45. 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 46. 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 47. 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 48. 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 49. 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 50. 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 51. 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 52. 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 53. 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 54. 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 55. 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 56. 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 57. 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 58. 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 59. 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 60. 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 61. 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 62. 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 63. 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 64. 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 65. 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 66. 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 67. 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 68. 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 69. 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 70. 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 71. 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 72. 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 73. 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 74. 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 75. 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 76. 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 77. 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 78. 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 79. 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 80. 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 81. 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 82. 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 83. 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 84. 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 85. 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 86. Trapping Rain Water LeetCode Solution In the Trapping Rain Water LeetCode 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 ...
Question 87. 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 88. 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 89. 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 90. 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 91. 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 92. 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 93. 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 94. 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 95. 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 96. 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 97. 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 98. 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 99. 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 100. 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 101. 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 102. 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 103. 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 104. 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 105. 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 106. 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 107. 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 108. 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 109. 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 110. 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 111. 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 112. 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 113. 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 114. 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 115. 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 116. 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 117. 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 118. 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 119. 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 120. 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 121. 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 122. 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 123. 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 124. 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 125. 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 126. 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 127. 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 128. 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 129. 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 130. 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 131. 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 132. 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 133. 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 134. 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 135. 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 136. 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 137. 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 138. 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 139. 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 140. 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 141. 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 142. 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 143. 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 144. 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 145. 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 146. Step-By-Step Directions From a Binary Tree Node to Another LeetCode Solution Problem Statement: Step-By-Step Directions From a Binary Tree Node to Another LeetCode Solution – You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination ...
Question 147. Shifting Letters LeetCode Solution Problem Statement Shifting Letters says that we have given a string s and an array shifts. Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times. We have to return the final string after all shifts are applied. Example 1: Input: s = "abc", shifts ...
Question 148. Score of Parenthesis LeetCode Solution Problem Statement The score of Parenthesis LeetCode Solution says – Given a balanced parentheses string s and return the maximum score. The score of a balanced parenthesis string is based on the following rules: "()" has score 1. AB has score A + B, where A and B are balanced parenthesis strings. (A) has score 2 * A, where A is a ...
Question 149. Design Add and Search Words Data Structure LeetCode Solution Problem Statement: Design Add and Search Words Data Structure LeetCode Solution says – Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: WordDictionary() Initializes the object. void addWord(word) Adds word to the data structure, it can be matched later. bool search(word) Returns true if there ...
Question 150. Decode String Leetcode Solution Problem Statement The Decode String LeetCode Solution – “Decode String” asks you to convert the encoded string into a decoded string. The encoding rule is k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times where k is a positive integer. Example: Input: s = "3[a]2[bc]" Output: "aaabcbc" ...
Question 151. Substring with Concatenation of All Words Leetcode Solution Problem Statement The Substring with Concatenation of All Words LeetCode Solution – “Substring with Concatenation of All Words” states that given a string s and an array of string words where each word is of the same length. We need to return all starting indices of the substring that is ...
Question 152. Different Ways to Add Parentheses Leetcode Solution Problem Statement The Different Ways to Add Parentheses LeetCode Solution – “Different Ways to Add Parentheses” states that given a string expression of numbers and operators. We need to return all possible results from computing all different possible ways to group numbers and operators. Return the answer in any order. ...
Question 153. Generate Parentheses Leetcode Solution Problem Statement The Generate Parentheses LeetCode Solution – “Generate Parentheses” states that given the value of n. We need to generate all combinations of n pairs of parentheses. Return the answer in the form of a vector of strings of well-formed parentheses. Example: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Explanation: ...
Question 154. Minimum Remove to Make Valid Parentheses LeetCode Solution Problem Statement The Minimum Remove to Make Valid Parentheses LeetCode Solution – You are given a string s of ‘(‘, ‘)’ and lowercase English characters. Your task is to remove the minimum number of parentheses ( ‘(‘ or ‘)’, in any positions ) so that the resulting parentheses string is ...
Question 155. Longest Substring Without Repeating Characters Leetcode Solution Problem Statement The Longest Substring Without Repeating Characters LeetCode Solution – states that given the string s. We need to find the longest substring without repeating characters. Example: Input: s = "abcabcbb" Output: 3 Explanation: The longest substring with no characters being repeated is of length 3. The string is: “abc”. Input: s = "bbbbb" ...
Question 156. Longest Common Prefix Leetcode Solution Problem Statement The Longest Common Prefix LeetCode Solution – “Longest Common Prefix” states that given an array of strings. We need to find the longest common prefix among these strings. If there doesn’t exist any prefix, return an empty string. Example: Input: strs = ["flower","flow","flight"] Output: "fl" Explanation: “fl” is the longest ...
Question 157. Valid Palindrome II Leetcode Solution Problem Statement The Valid Palindrome II LeetCode Solution – “Valid Palindrome II” states that given the string s, we need to return true if s can be a palindrome string after deleting at most one character. Example: Input: s = "aba" Output: true Explanation: The input string is already palindrome, so there’s ...
Question 158. Valid Parentheses Leetcode Solution Problem Statement The Valid Parentheses LeetCode Solution – “Valid Parentheses” states that you’re given a string containing just the characters '(', ')', '{', '}', '[' and ']'. We need to determine whether the input string is a valid string or not. A string is said to be a valid string if open brackets must be closed ...
Question 159. Largest Number Leetcode Solution Problem Statement The Largest Number LeetCode Solution – “Largest Number” states that given a list of non-negative integers nums, we need to arrange the numbers in such a way that they form the largest number and return it. Since the result may be very large, so you need to return ...
Question 160. Implement Trie (Prefix Tree) Leetcode Solution Problem Statement The Implement Trie (Prefix Tree) LeetCode Solution – “Implement Trie (Prefix Tree)” asks you to implement the Trie Data Structure that performs inserting, searching and prefix searching efficiently. Example: Input: ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] Output: [null, null, true, false, true, null, true] Explanation: After inserting all the strings, trie looks like this. Word apple is searched which ...
Question 161. Palindrome Partitioning Leetcode Solution Problem Statement The Palindrome Partitioning LeetCode Solution – “Palindrome Partitioning” states that you’re given a string, partition the input string such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of the input string. Example: Input: s = "aab" Output: [["a","a","b"],["aa","b"]] Explanation: There exist exactly 2 valid ...
Question 162. Count and Say Leetcode Solution Problem Statement The Count and Say LeetCode Solution – “Count and Say” asks you to find the nth term of the count-and-say sequence. The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = "1" countAndSay(n) is the way you would “say” the digit string from countAndSay(n-1), which is then converted ...
Question 163. Palindromic Substrings Leetcode Solution Problem Statement The Palindromic Substrings LeetCode Solution – “Palindromic Substrings” asks you to find a total number of palindromic substrings in the input string. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string. Example: Input: s = "aaa" Output: ...
Question 164. Remove Invalid Parentheses Leetcode Solution Problem Statement The Remove Invalid Parentheses Leetcode Solution – states that you’re given a string s that contains parenthesis and lowercase letters. We need to remove the minimum number of invalid parentheses to make the input string valid. We need to return all possible results in any order. A string is ...
Question 165. 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 166. 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 167. 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 168. 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 169. 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 170. 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 171. 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 172. 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 173. 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 174. 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 175. 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 176. 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 177. 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 178. 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 179. 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 180. Longest Substring Without Repeating Characters LeetCode Solution Longest Substring Without Repeating Characters LeetCode Solution – 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 ...
Question 181. 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 182. Text Justification LeetCode Solution We will discuss Text Justification LeetCode Solution today 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 ...
Question 183. 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 184. 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 185. 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 186. 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 187. 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 188. 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 189. 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 190. 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 191. 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 192. 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 193. 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 194. 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 195. 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 196. 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 197. Valid Parentheses LeetCode Solution In Valid Parentheses LeetCode problem we have given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid. Here we will provide a Valid Parentheses LeetCode Solution to you. An input string is valid if: Open brackets must be closed ...
Question 198. 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 199. 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 200. 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 201. 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 202. 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 203. 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 204. 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 205. 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 206. 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 207. 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 208. 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 209. 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 210. 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 211. 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 212. 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 213. 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 214. 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 215. 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 216. Lowest Common Ancestor of a Binary Search Tree Leetcode Solution Problem Statement: Lowest Common Ancestor of a Binary Search Tree Leetcode Solution – Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. Note: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as ...
Question 217. Step-By-Step Directions From a Binary Tree Node to Another LeetCode Solution Problem Statement: Step-By-Step Directions From a Binary Tree Node to Another LeetCode Solution – You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination ...
Question 218. Vertical Order Traversal of Binary Tree LeetCode Solution Problem Statement Vertical Order Traversal of Binary Tree LeetCode Solution says – Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. ...
Question 219. Sum Root to Leaf Numbers LeetCode Solution Problem Statement Sum Root to Leaf Numbers LeetCode Solution says – You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. Return the total sum of all root-to-leaf numbers. Test ...
Question 220. Binary Tree Inorder Traversal LeetCode Solution Problem Statement: Binary Tree Inorder Traversal LeetCode solution Given the root of a binary tree, return the inorder traversal of its nodes’ values. Example 1: Input: root = [1,null,2,3] Output: [1,3,2] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] Constraints: The number of nodes in ...
Question 221. Flatten Binary Tree to Linked List LeetCode Solution Flatten Binary Tree to Linked List LeetCode Solution says that – Given the root of a binary tree, flatten the tree into a “linked list”: The “linked list” should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The “linked list” ...
Question 222. Diameter of N-Ary Tree LeetCode Solution Problem Statement : The Diameter of N-Ary Tree LeetCode Solution – Given a root of an N-ary tree, you need to compute the length of the diameter of the tree. The diameter of an N-ary tree is the length of the longest path between any two nodes in the tree. This path may or may not ...
Question 223. Lowest Common Ancestor of a Binary Tree Leetcode Solution Problem Statement The Lowest Common Ancestor of a Binary Tree LeetCode Solution – “Lowest Common Ancestor of a Binary Tree” states that given the root of the binary tree and two nodes of the tree. We need to find the lowest common ancestor of these two nodes. The Lowest Common ...
Question 224. Populating Next Right Pointers in Each Node Leetcode Solution Problem Statement The Populating Next Right Pointers in Each Node LeetCode Solution – “Populating Next Right Pointers in Each Node” states that given the root of the perfect binary tree and we need to populate each next pointer of the node to its next right node. If there is no next ...
Question 225. Delete Nodes and Return Forest Leetcode Solution Problem Statement The Delete Nodes and Return Forest LeetCode Solution – “Delete Nodes and Return Forest” states that given the root of the binary tree where each node has a distinct value. We’re also given an array, to_delete, where we need to delete all the nodes with values contained in ...
Question 226. Symmetric Tree Leetcode Solution Problem Statement The Symmetric Tree LeetCode Solution – “Symmetric Tree” states that given the root of the binary tree and we need to check if the given binary tree is a mirror of itself (symmetric around its center) or not? If Yes, we need to return true otherwise, false. Example: ...
Question 227. 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 228. 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 229. 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 230. 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 231. 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 232. 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 233. 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 234. 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 235. 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 236. 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 237. 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 238. 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 239. 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 240. 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 241. 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 242. 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 243. 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 244. 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 245. 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 246. Is Graph Bipartite? LeetCode Solution Problem Statement Is Graph Bipartite LeetCode Solution- There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has ...
Question 247. 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 248. 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 249. 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 250. 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 251. 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 252. Score of Parenthesis LeetCode Solution Problem Statement The score of Parenthesis LeetCode Solution says – Given a balanced parentheses string s and return the maximum score. The score of a balanced parenthesis string is based on the following rules: "()" has score 1. AB has score A + B, where A and B are balanced parenthesis strings. (A) has score 2 * A, where A is a ...
Question 253. Binary Tree Inorder Traversal LeetCode Solution Problem Statement: Binary Tree Inorder Traversal LeetCode solution Given the root of a binary tree, return the inorder traversal of its nodes’ values. Example 1: Input: root = [1,null,2,3] Output: [1,3,2] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] Constraints: The number of nodes in ...
Question 254. Decode String Leetcode Solution Problem Statement The Decode String LeetCode Solution – “Decode String” asks you to convert the encoded string into a decoded string. The encoding rule is k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times where k is a positive integer. Example: Input: s = "3[a]2[bc]" Output: "aaabcbc" ...
Question 255. Flatten Binary Tree to Linked List LeetCode Solution Flatten Binary Tree to Linked List LeetCode Solution says that – Given the root of a binary tree, flatten the tree into a “linked list”: The “linked list” should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The “linked list” ...
Question 256. Add Two Numbers II Leetcode Solution Problem Statement The Add Two Numbers II LeetCode Solution – “Add Two Numbers II” states that two non-empty linked lists represent two non-negative integers where the most significant digit comes first and each node contains exactly one digit. We need to add the two numbers and return the sum as ...
Question 257. Daily Temperatures Leetcode Solution Problem Statement The Daily Temperatures Leetcode Solution: states that given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead. ...
Question 258. Minimum Remove to Make Valid Parentheses LeetCode Solution Problem Statement The Minimum Remove to Make Valid Parentheses LeetCode Solution – You are given a string s of ‘(‘, ‘)’ and lowercase English characters. Your task is to remove the minimum number of parentheses ( ‘(‘ or ‘)’, in any positions ) so that the resulting parentheses string is ...
Question 259. Trapping Rain Water Leetcode Solution Problem Statement The Trapping Rain Water LeetCode Solution – “Trapping Rain Water” states that given an array of heights which represents an elevation map where the width of each bar is 1. We need to find the amount of water trapped after rain. Example: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: Check ...
Question 260. Valid Parentheses Leetcode Solution Problem Statement The Valid Parentheses LeetCode Solution – “Valid Parentheses” states that you’re given a string containing just the characters '(', ')', '{', '}', '[' and ']'. We need to determine whether the input string is a valid string or not. A string is said to be a valid string if open brackets must be closed ...
Question 261. Maximum Frequency Stack Leetcode Solution Problem Statement The Maximum Frequency Stack LeetCode Solution – “Maximum Frequency Stack” asks you to design a frequency stack in which whenever we pop an element from the stack, it should return the most frequent element present in the stack. Implement the FreqStack class: FreqStack() constructs an empty frequency stack. void push(int val) pushes ...
Question 262. 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 263. Trapping Rain Water LeetCode Solution In the Trapping Rain Water LeetCode 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 ...
Question 264. 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 265. 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 266. 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 267. 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 268. Moving Average from Data Stream Leetcode Solution Problem Statement The Moving Average from Data Stream LeetCode Solution – “Moving Average from Data Stream” states that given a stream of integers and a window size k. We need to calculate the moving average of all the integers in the sliding window. If the number of elements in the ...
Question 269. 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 270. 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 271. 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 272. Best Meeting Point LeetCode Solution Problem Statement: Best Meeting Point Leetcode Solution says – Given a m x n binary grid grid where each 1 marks the home of one friend, return the minimal total travel distance. The total travel distance is the sum of the distances between the houses of the friends and the meeting point. The distance is calculated using Manhattan Distance, ...
Question 273. Minimum Path Sum Leetcode Solution Problem Statement The Minimum Path Sum LeetCode Solution – “Minimum Path Sum” says that given a n x m grid consisting of non-negative integers and we need to find a path from top-left to bottom right, which minimizes the sum of all numbers along the path. We can only move ...
Question 274. Unique Paths II Leetcode Solution Problem Statement The Unique Paths II LeetCode Solution – “Unique Paths II” states that given the m x n grid where a robot starts from the top left corner of the grid. We need to find the total number of ways to reach the bottom right corner of the grid. ...
Question 275. Search a 2D Matrix II Leetcode Solution Problem Statement The Search a 2D Matrix II LeetCode Solution – “Search a 2D Matrix II”asks you to find an efficient algorithm that searches for a value target in an m x n integer matrix matrix. Integers in each row, as well as column, are sorted in ascending order. Example: Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 Output: true ...
Question 276. Set Matrix Zeroes Leetcode Solution Problem Statement The Set Matrix Zeroes LeetCode Solution – “Set Matrix Zeroes” states that you’re given an m x n integer matrix matrix.We need to modify the input matrix such that if any cell contains the element 0, then set its entire row and column to 0‘s. You must do it in ...
Question 277. 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 278. 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 279. 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 280. 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 281. 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 282. 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 283. 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 284. 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 285. 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 286. 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 287. 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 288. 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 289. 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 290. Unique Paths III LeetCode Solution Problem Statement: Unique Paths III LeetCode Solution: You are given an m x n integer array grid where grid[i][j] could be: 1 representing the starting square. There is exactly one starting square. 2 representing the ending square. There is exactly one ending square. 0 representing empty squares we can walk over. -1 representing obstacles that we cannot walk over. Return the ...
Question 291. Invert Binary Tree LeetCode Solution Problem Statement: Invert Binary Tree LeetCode Solution : Given the root of a binary tree, invert the tree, and return its root. An inverted form of a Binary Tree is another Binary Tree with left and right children of all non-leaf nodes interchanged. You may also call it the mirror of the input tree. ...
Question 292. Implement strStr() LeetCode Solution Problem Statement: Implement strStr() LeetCode Solution – Implement strStr(). Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we ...
Question 293. Break a Palindrome LeetCode Solution Problem Statement: Break a Palindrome LeetCode Solution: Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible. Return the resulting string. If there is no way to replace a character to make ...
Question 294. Contains Duplicate LeetCode Solution Problem Statement: Contains Duplicate LeetCode Solution says that- Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: ...
Question 295. Best Time to Buy and Sell Stock IV LeetCode Solution Problem Statement: Best Time to Buy and Sell Stock IV LeetCode Solution: You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k. Find the maximum profit you can achieve. You may complete at most k transactions. Note: You may not engage in multiple transactions simultaneously ...
Question 296. Find First and Last Position of Element in Sorted Array LeetCode Solution Problem Statement: Find First and Last Position of Element in Sorted Array LeetCode Solution says that – given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity. ...
Question 297. Find Peak Element LeetCode Solution Problem Statement Find Peak Element LeetCode Solution says that – A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine ...
Question 298. Valid Anagram Leetcode Solution Problem Statement Valid Anagram Leetcode Solution – Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: s = "anagram", t = "nagaram" Output: ...
Question 299. Next Permutation LeetCode Solution Problem Statement Next Permutation LeetCode Solution – A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are considered permutations of arr: [1,2,3], [1,3,2], [3,1,2], [2,3,1]. The next permutation of an array of integers is the next lexicographically greater permutation of ...
Question 300. Minimum Number of Arrows to Burst Balloons LeetCode Solution Problem Statement: Minimum Number of Arrows to Burst Balloons LeetCode Solution: There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of ...
Question 301. Flatten Binary Tree to Linked List LeetCode Solution Problem Statement: Flatten Binary Tree to Linked List LeetCode Solution: Given the root of a binary tree, flatten the tree into a “linked list”: The “linked list” should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The “linked list” should be ...
Question 302. Next Greater Element I Leetcode Solution Problem Statement Next Greater Element I Leetcode Solution – The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine ...
Question 303. Next Greater Element II LeetCode Solution Problem Statement Next Greater Element II LeetCode Solution – Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing order next in the array, which means you could search ...
Question 304. Group Shifted Strings Leetcode Solution Problem Statement Group Shifted Strings Leetcode Solution – We can shift a string by shifting each of its letters to its successive letter. For example, "abc" can be shifted to be "bcd". We can keep shifting the string to form a sequence. For example, we can keep shifting "abc" to form the sequence: "abc" -> "bcd" ...
Question 305. Peak Index in a Mountain Array LeetCode Solution Problem Statement Peak Index in a Mountain Array LeetCode Solution – An array arr a mountain if the following properties hold: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > ...
Question 306. Swim in Rising Water LeetCode Solution Problem Statement: Swim in Rising Water LeetCode Solution : You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if ...
Question 307. Unique Binary Search Trees LeetCode Solution Unique Binary Search Trees LeetCode Solution says that – Given an integer n, return the number of structurally unique BST’s (binary search trees) which has exactly n nodes of unique values from 1 to n. Example 1: Input: n = 3 Output: 5 Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 19 ...
Question 308. Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution Problem Statement: Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution: RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element. Implement the RandomizedCollection class: RandomizedCollection() Initializes the empty RandomizedCollection object. bool insert(int val) Inserts an item val into ...
Question 309. Range Sum of BST LeetCode Solution Range Sum of BST LeetCode Solution says that – Given the root the node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high]. Example 1: Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 Output: 32 Explanation: ...
Question 310. Reverse Integer Leetcode Solution Problem Statement Reverse Integer LeetCode Solution says that – Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: ...
Question 311. Find K Closest Elements LeetCode Solution Problem Statement Find K Closest Elements LeetCode Solution – Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| < |b - x|, or |a - x| == |b - ...
Question 312. Sort Colors LeetCode Solution Problem Statement Sort Colors LeetCode Solution – Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. ...
Question 313. Excel Sheet Column Number LeetCode Solution Problem Statement Excel Sheet Column Number LeetCode Solution says that Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... ...
Question 314. Longest Common Subsequence LeetCode Solution Problem Statement Longest Common Subsequence LeetCode Solution – Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining ...
Question 315. Range Sum Query 2D – Immutable LeetCode Solution Problem Statement Range Sum Query 2D – Immutable LeetCode Solution – Given a 2D matrix, handle multiple queries of the following type: Calculate the sum of the elements of the matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Implement the NumMatrix class: NumMatrix(int[][] ...
Question 316. Total Hamming Distance LeetCode Solution Problem Statement: Total Hamming Distance LeetCode Solution: Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums. The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Example 1: Input: nums = [4,14,2] Output: 6 Explanation: In binary representation, ...
Question 317. Shortest Unsorted Continuous Subarray LeetCode Solution Problem Statement Shortest Unsorted Continuous Subarray LeetCode Solution says that – Given an integer array nums, you have to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the length of the shortest subarray. Example 1: ...
Question 318. Rectangle Overlap LeetCode Solution Problem Statement: Rectangle Overlap LeetCode Solution – says that An axis-aligned rectangle is represented as a list, [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left ...
Question 319. Greatest Sum Divisible by Three LeetCode Solution Problem Statement: Greatest Sum Divisible by Three LeetCode Solution: Array nums of integers are given, we need to find the maximum possible sum of elements of the array such that it is divisible by three. Example 1: Input: nums = [3,6,5,1,8] Output: 18 Explanation: Pick numbers 3, 6, 1 and ...
Question 320. Insert into a Sorted Circular Linked List LeetCode Solution Problem Statement: Insert into a Sorted Circular Linked List LeetCode Solution – says that Given a Circular Linked List node, which is sorted in ascending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. The given node can be a ...
Question 321. Odd Even Linked List Leetcode Solution Problem Statement The Odd-Even Linked List LeetCode Solution – “Odd-Even Linked List” states that given a non-empty singly linked list. We need to group all nodes with odd indices together followed by the nodes with even indices, and return the reordered list. Note that the relative order inside both the ...
Question 322. Design A Leaderboard Leetcode Solution Problem Statement The Design A Leaderboard LeetCode Solution – “Design A Leaderboard” asks you to complete 3 functions: addScore(playerId, score): Update the leaderboard by adding a score to the given player’s score. If there doesn’t exist any player, add such id on the leaderboard. top(K): Return the top sum of ...
Question 323. Divide Two Integers Leetcode Solution Problem Statement The Divide Two Integers LeetCode Solution – “Divide Two Integers” states that you’re given two integers dividend and divisor. Return the quotient after dividing the dividend by the divisor. Note that we’re assuming that we’re dealing with an environment that could store integers within a 32-bit signed integer ...
Question 324. Robot Room Cleaner Leetcode Solution Problem Statement The Robot Room Cleaner LeetCode Solution – “Robot Room Cleaner” states that given the robot in a m x n a binary grid where 0 represents a wall and 1 represents an empty slot. The initial position of the robot is guaranteed to be empty and the robot moves inside the ...
Question 325. LRU Cache Leetcode Solution Problem Statement The LRU Cache LeetCode Solution – “LRU Cache” asks you to design a data structure that follows Least Recently Used (LRU) Cache We need to implement LRUCache class that has the following functions: LRUCache(int capacity): Initializes the LRU cache with positive size capacity. int get(int key): Return the value ...
Question 326. Merge k Sorted Lists Leetcode Solution Problem Statement The Merge k Sorted Lists LeetCode Solution – “Merge k Sorted Lists” states that given the array of k linked lists, where each linked list has its values sorted in ascending order. We need to merge all the k-linked lists into one single linked list and return the ...
Question 327. Range Sum Query 2D – Immutable Leetcode Solution Problem Statement Range Sum Query 2D – Immutable Leetcode Solution – Given a 2D matrix matrix, handle multiple queries of the following type: Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Implement the NumMatrix class: NumMatrix(int[][] matrix) Initializes the object with the integer ...
Question 328. Partition Labels LeetCode Solution Problem Statement Partition Labels LeetCode Solution – You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the ...
Question 329. Flipping an Image LeetCode Solution Problem Statement Flipping an Image LeetCode Solution – We are given a matrix of size n. We need to perform 2 tasks- flip the image horizontally: it means each row of the given matrix is reversed invert the image: make all 0’s to 1’s & vice versa Return the resulting ...
Question 330. Fibonacci Number LeetCode Solution Problem Statement Fibonacci Number LeetCode Solution – “Fibonacci Number” states that The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n ...
Question 331. Diagonal Traversal LeetCode Solution Problem Statement Diagonal Traversal LeetCode Solution – Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images. Input: nums = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,4,2,7,5,3,8,6,9] Explanation for Diagonal Traversal LeetCode Solution Key Idea The first row and the last column in this problem would serve ...
Question 332. Nearest Exit from Entrance in Maze LeetCode Solution Problem Statement Nearest Exit from Entrance in Maze LeetCode Solution – We are given an m x n matrix “maze” (0-indexed) with empty cells represented as ‘.’ and walls as ‘+’. You are also given the entrance of the maze, where entrance = [entrance_row, entrance_col] denotes the row and column ...
Question 333. Valid Tic-Tac-Toe State LeetCode Solution Problem Statement Valid Tic-Tac-Toe State LeetCode Solution – We are given a Tic-Tac-Toe board as a string array board & are asked to return true iff it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array ...
Question 334. Reverse Words in a String III LeetCode Solution Problem Statement Reverse Words in a String III LeetCode Solution – We are given a string and are asked to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Examples & Explanations Example 1: Input: s = "Let's take LeetCode ...
Question 335. Remove Duplicates from Sorted List LeetCode Solution Problem Statement Remove Duplicates from Sorted List LeetCode Solution – We are given the head of a sorted linked list. We are asked to delete all the duplicates such that each element appears only once and return the linked list sorted as well. Examples & Explanations Example 1: Input: head ...
Question 336. Clone Graph LeetCode Solution Problem Statement Clone Graph LeetCode Solution – We are given a reference of a node in a connected undirected graph and are asked to return a deep copy of the graph. A deep copy is basically a clone where no node present in the deep copy should have the reference ...
Question 337. Minimum Height Trees LeetCode Solution Problem Statement Minimum Height Trees LeetCode Solution – We are given a tree of n nodes labelled from 0 to n-1 as a 2D array “edges” where edge[i] = [a_i, b_i] indicates that there is an undirected edge between the two nodes a_i and b_i in the tree. We have ...
Question 338. Kth Smallest Element in a Sorted Matrix LeetCode Solution Problem Statement Kth Smallest Element in a Sorted Matrix LeetCode Solution – We are given a matrix of size n where each of the rows and columns is sorted in ascending order. We are asked to return the kth smallest element in the matrix. Note that it is the kth ...
Question 339. Number of Islands II LeetCode Solution Problem Statement Number of Islands II LeetCode Solution – You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0‘s represent water and 1‘s represent land. Initially, all the cells grid are water cells (i.e., all the cells are 0‘s). We may perform an add land ...
Question 340. Remove Duplicates from Sorted List II LeetCode Solution Problem Statement Remove Duplicates from Sorted List II LeetCode Solution – Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Input: head = [1,2,3,3,4,4,5] Output: [1,2,5] Explanation The idea here is to traverse ...
Question 341. Shortest Path in a Grid with Obstacles Elimination LeetCode Solution Problem Statement Shortest Path in a Grid with Obstacles Elimination LeetCode Solution – You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left ...
Question 342. Can Place Flowers LeetCode Solution Problem Statement Can Place Flowers LeetCode Solution – You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0‘s and 1‘s, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in ...
Question 343. First Unique Character in a String LeetCode Solution Problem Statement First Unique Character in a String LeetCode Solution – Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. Example Test Case 1: Input: s = “leetcode” Output: 0 Test Case 2: Input: s = “aabb” Output: -1 Explanation ...
Question 344. Invert Binary Tree LeetCode Solution Problem Statement: Invert Binary Tree LeetCode Solution – In this question, Given a root of any binary tree, the solution is required to invert the binary tree meaning the left tree should become the right tree and vice versa. Explanation We can ask ourselves which tree traversal would be ...
Question 345. Closest Binary Search Tree Value Leetcode Solution Problem Statement : Closest Binary Search Tree Value Leetcode Solution – Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. Example : Example 1 Input: root = [4,2,5,1,3], target = 3.714286 Output: 4 Example 2 Input: root = [1], target ...
Question 346. Partition List Leetcode Solution Problem Statement : Partition List Leetcode Solution – Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example : Example 1 Input: head = ...
Question 347. Evaluate Reverse Polish Notation LeetCode Solution Problem Statement Evaluate Reverse Polish Notation LeetCode Solution – Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that the division between two integers should truncate toward zero. It is guaranteed that the given ...
Question 348. 3Sum Closest LeetCode Solution Problem Statement 3Sum Closest LeetCode Solution – Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Input: nums = [-1,2,1,-4], target = 1 Output: ...
Question 349. Largest Plus Sign Leetcode Solution Problem Statement : Largest Plus Sign Leetcode Solution – You are given an integer n. You have an n x n binary grid with all values initially 1‘s except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0. Return the order of the largest axis-aligned plus ...
Question 350. Contiguous Array LeetCode Solution Problem Statement Contiguous Array LeetCode Solution – Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1. Input: nums = [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. Explanation Now what we ...
Question 351. Maximum Number of Occurrences of a Substring Leetcode Solution Problem Statement : Maximum Number of Occurrences of a Substring Leetcode Solution – Given a string s, return the maximum number of occurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size must be between minSize and maxSize inclusive. Example ...
Question 352. Nested List Weight Sum II LeetCode Solution Problem Statement Nested List Weight Sum II LeetCode Solution – You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. The depth of an integer is the number of lists that it is inside of. For ...
Question 353. N-Queens LeetCode Solution Problem Statement N-Queens LeetCode Solution – The n-queens puzzle is the problem of placing n queens on a n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the ...
Question 354. Largest Rectangle in Histogram LeetCode Solution Problem Statement Largest Rectangle in Histogram LeetCode Solution – Given an array of integers heights representing the histogram’s bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. Example Test Case 1: Input: heights = [2, 1, 5, 6, 2, 3] Output: 10 Explanation: ...
Question 355. Regular Expression Matching Regular Expression Matching LeetCode Solution Problem Statement Regular Expression Matching Regular Expression Matching LeetCode Solution – Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Example Test Case 1: Input: ...
Question 356. Binary Tree Right Side View LeetCode Solution Problem Statement Binary Tree Right Side View LeetCode Solution – Given the root of a binary tree, imagine yourself standing on the right side of it, and return the values of the nodes you can see ordered from top to bottom. Example Test Case 1: Input: root = [1, 2, 3, null, 5, null, ...
Question 357. Zigzag Conversion LeetCode Solution Problem Statement Zigzag Conversion LeetCode Solution – The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I ...
Question 358. Third Maximum Number Leetcode Solution Problem Statement Third Maximum Number Leetcode Solution – Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. Example Input: nums = [3,2,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third ...
Question 359. Minesweeper LeetCode Solution Problem Statement Minesweeper LeetCode Solution – Let’s play the minesweeper game (Wikipedia, online game)! You are given an m x n char matrix board representing the game board where: 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all ...
Question 360. Koko Eating Bananas LeetCode Solution Problem Statement Koko Eating Bananas LeetCode Solution – Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If ...
Question 361. Time Based Key-Value Store LeetCode Solution Problem Statement Time Based Key-Value Store LeetCode Solution – Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key’s value at a certain timestamp. Implement the TimeMap class: TimeMap() Initializes the object of the data structure. void set(String key, String ...
Question 362. Find Median from Data Stream LeetCode Solution Problem Statement Find Median from Data Stream LeetCode Solution – The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values. For example, for arr = [2,3,4], the median ...
Question 363. Permutation in String Leetcode Solution Problem Statement : Permutation in String Leetcode Solution – Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1‘s permutations is the substring of s2. Example : Example 1 Input: s1 = "ab", s2 = "eidbaooo" Output: true Explanation: s2 contains one permutation of s1 ("ba"). ...
Question 364. Asteroid Collision LeetCode Solution Problem Statement Asteroid Collision LeetCode Solution – We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state ...
Question 365. Diagonal Traverse LeetCode Solution Problem Statement Diagonal Traverse LeetCode Solution – Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order. Input: mat = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,4,7,5,3,6,8,9] Explanation Consider the indices of the diagonals of an NxM matrix. Let’s use a 4×4 matrix as an example: ...
Question 366. Longest Increasing Path in a Matrix LeetCode Solution Problem Statement Longest Increasing Path in a Matrix LeetCode Solution – Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). Input: ...
Question 367. Number of Closed Islands Leetcode Solution Problem Statement : Number of Closed Islands Leetcode Solution – Given a 2D grid consisting of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands. Example : Example 1 Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]] Output: 2 Explanation: Islands in gray ...
Question 368. Serialize and Deserialize Binary Tree LeetCode Solution Problem Statement Serialize and Deserialize Binary Tree LeetCode Solution – Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in ...
Question 369. Binary Tree Maximum Path Sum LeetCode Solution Problem Statement Binary Tree Maximum Path Sum LeetCode Solution – A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need ...
Question 370. Minimum Knight Moves LeetCode Solution Problem Statement Minimum Knight Moves LeetCode Solution – In an infinite chessboard with coordinates from -infinity to +infinity, you have a knight at square [0, 0]. A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Return the minimum number ...
Question 371. Minimum Number of Taps to Open to Water a Garden LeetCode Solution Problem Statement Minimum Number of Taps to Open to Water a Garden LeetCode Solution – There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in ...
Question 372. Binary Tree Zigzag Level Order Traversal LeetCode Solution Problem Statement Binary Tree Zigzag Level Order Traversal LeetCode Solution – Given the root of a binary tree, return the zigzag level order traversal of its nodes’ values. (i.e., from left to right, then right to left for the next level and alternate between). Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]] Explanation We ...
Question 373. Find the Duplicate Number LeetCode Solution Problem Statement Find the Duplicate Number LeetCode Solution – Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space. Input: nums = [1,3,4,2,2] Output: 2 Explanation ...
Question 374. Missing Element in Sorted Array LeetCode Solution Problem Statement: Missing Element in Sorted Array LeetCode Solution – Given an integer array nums which are sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array. Example: Example 1 Input: nums = [4,7,9,10], k = ...
Question 375. Path Sum II LeetCode Solution Problem Statement : Path Sum II LeetCode Solution – Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. A root-to-leaf path is a path starting from ...
Question 376. Alien Dictionary LeetCode Solution Problem Statement Alien Dictionary LeetCode Solution – There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you. You are given a list of strings words from the alien language’s dictionary, where the strings in words are sorted lexicographically by the rules of this new language. ...
Question 377. Product of Array Except Self LeetCode Solution Problem Statement Product of Array Except Self LeetCode Solution – Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division ...
Question 378. Design Skiplist LeetCode Solution Problem Statement Design Skiplist LeetCode Solution – Design a Skiplist without using any built-in libraries. A skip list is a data structure that takes O(log(n)) time to add, erase and search. Compared with the tree and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively ...
Question 379. Scramble String LeetCode Solution Problem Statement Scramble String LeetCode Solution – We can scramble a string s to get a string t using the following algorithm: If the length of the string is 1, stop. If the length of the string is > 1, do the following: Split the string into two non-empty substrings ...
Question 380. Sum of Left Leaves LeetCode Solution Problem Statement: Sum of Left Leaves LeetCode Solution – Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. Example & Explanation: Input: root = [3,9,20,null,null,15,7] Output: 24 Explanation: There ...
Question 381. Palindrome Permutation LeetCode Solution Problem Statement Palindrome Permutation LeetCode Solution – We are given a string and asked if a permutation of the given string could form a palindrome. Examples & Explanations Example 1: Input: s = "code" Output: false Explanation: we can not arrange letters of "code" to form a palindrome Example 2: ...
Question 382. Intersection of Two Linked Lists LeetCode Solution Problem Statement Intersection of Two Linked Lists LeetCode Solution – We are given the heads of two strongly linked-lists headA and headB. It is also given that the two linked lists may intersect at some point. We are asked to return the node at which they intersect or null if ...
Question 383. Permutation Sequence LeetCode Solution Problem Statement Permutation Sequence LeetCode Solution – The set [1, 2, 3, ..., n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Example Test Case 1: Input: n ...
Question 384. Find Largest Value in Each Tree Row LeetCode Solution Problem Statement Find Largest Value in Each Tree Row LeetCode Solution – Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed). Example Test Case 1: Input: root = [1, 3, 4, 5, 3, null, 9] Output: [1, 3, 9] Explanation 1, 3, and ...
Question 385. Search Suggestions System LeetCode Solution Problem Statement Search Suggestions System LeetCode Solution – You are given an array of strings products and a string searchWord. Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have a common prefix with searchWord. If there are more than three products with a ...
Question 386. Rotate Image LeetCode Solution Problem Statement Rotate Image LeetCode Solution – You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example Test Case 1: Input: ...
Question 387. Peeking Iterator LeetCode Solution Problem Statement Peeking Iterator LeetCode Solution – Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations. Implement the PeekingIterator class: PeekingIterator(Iterator<int> nums) Initializes the object with the given integer iterator iterator. int next() Returns the next element in the array and moves the pointer to the next element. boolean ...
Question 388. Defanging an IP Address LeetCode Solution Problem Statement Defanging an IP Address LeetCode Solution – Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period "." with "[.]". Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1" Explanation The intuition is very simple. 1. create a Stringbuilder str 2. loop through the address string ...
Question 389. Kth Smallest Element in a BST Leetcode Solution Problem Statement Kth Smallest Element in a BST Leetcode Solution – Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. Examples: Input: root = [3,1,4,null,2], k = 1 Output: 1 Input: root = [5,3,6,2,4,null,null,1], k ...
Question 390. Friends Of Appropriate Ages LeetCode Solution Problem Statement : Friends Of Appropriate Ages LeetCode Solution – There are n persons on a social media website. You are given an integer array of ages where ages[i] is the age of the ith person. A Person x will not send a friend request to a person y (x != y) if any of the following conditions is ...
Question 391. Find Leaves of Binary Tree LeetCode Solution Problem Statement Find Leaves of Binary Tree LeetCode Solution – Given the root of a binary tree, collect a tree’s nodes as if you were doing this: Collect all the leaf nodes. Remove all the leaf nodes. Repeat until the tree is empty. Example Test Case 1: Input: root = [1, 2, 3, ...
Question 392. Top K Frequent Words LeetCode Solution Problem Statement Top K Frequent Words LeetCode Solution – Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order. Example Test Case 1: Input: words = [“i”,”love”,”leetcode”,”i”,”love”,”coding”] k = 2 Output: [“i”,”love”] Explanation ...
Question 393. Increasing Triplet Subsequence LeetCode Solution Problem Statement : Increasing Triplet Subsequence LeetCode Solution – Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. Example : Example 1: Input: nums = [2,1,5,0,4,6] Output: true Explanation: The ...
Question 394. Merge Sorted Array LeetCode Solution Problem Statement Merge Sorted Array LeetCode Solution – You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. ...
Question 395. Employee Free Time LeetCode Solution Problem Statement Employee Free Time LeetCode Solution – We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing the common, positive-length free time for all employees, also in ...
Question 396. Swapping Nodes in a Linked List Leetcode Solution Problem Statement Swapping Nodes in a Linked List Leetcode Solution – You are given the head of a linked list, and an integer k.Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). Example: Input: head = [1,2,3,4,5], k = 2 ...
Question 397. Find Minimum in Rotated Sorted Array II LeetCode Solution Problem Statement Find Minimum in Rotated Sorted Array II LeetCode Solution – Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: [4,5,6,7,0,1,4] if it was rotated 4 times. [0,1,4,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ...
Question 398. Delete Node in a Linked List Leetcode Solution Problem Statement : Delete Node in a Linked List Leetcode Solution – Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead, you will be given access to the node to be deleted directly. It is guaranteed that the node to be deleted is not ...
Question 399. Number of Distinct Islands Leetcode Solution Problem Statement The Number of Distinct Islands LeetCode Solution – “Number of Distinct Islands” states that given a n x m binary matrix. An island is a group of 1‘s (representing land) connected 4-directionally (horizontal or vertical). An island is considered to be the same as another if and only if one island ...
Question 400. Closest Leaf in a Binary Tree LeetCode Solution Problem Statement Closest Leaf in a Binary Tree LeetCode Solution – Given the root of a binary tree where every node has a unique value and a target integer k, return the value of the nearest leaf node to the target k in the tree. Nearest to a leaf means the least number of edges traveled on the binary tree to ...
Question 401. Ugly Number II LeetCode Solution Problem Statement Ugly Number II LeetCode Solution – An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number. Input: n = 10 Output: 12 Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ...
Question 402. Find a Peak Element II LeetCode Solution Problem Statement Find a Peak Element II LeetCode Solution – A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j]. You may assume ...
Question 403. Combination Sum IV LeetCode Solution Problem Statement Combination Sum IV LeetCode Solution – Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target. The test cases are generated so that the answer can fit in a 32-bit integer. Input: nums = [1,2,3], target = 4 Output: 7 Explanation: The possible ...
Question 404. String to Integer (atoi) LeetCode Solution Problem Statement The String to Integer (atoi) Leetcode Solution -“String to Integer (atoi)” states that Implementing the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi function). The algorithm for myAtoi(string s) is as follows: Read in and ignore any leading whitespace. Check if the next character (if ...
Question 405. Restore IP Addresses Leetcode Solution Problem Statement The Restore IP Addresses LeetCode Solution – “Restore IP Addresses” states that given the string which contains only digits, we need to return all possible valid IP Addresses in any order that can be formed by inserting dots into the string. Note that we’re not allowed to return ...
Question 406. String Compression LeetCode Solution Problem Statement String Compression LeetCode Solution – Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group’s length is 1, append the character to s. Otherwise, append the character followed by the group’s length. The compressed string ...
Question 407. Minimum Swaps To Make Sequences Increasing LeetCode Solution Problem Statement Minimum Swaps To Make Sequences Increasing LeetCode Solution – You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i]. For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8]. ...
Question 408. Check Completeness of a Binary Tree LeetCode Solution Problem Statement Check Completeness of a Binary Tree LeetCode Solution – Given the root of a binary tree, determine if it is a complete binary tree. In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. ...
Question 409. Graph Valid Tree LeetCode Solution Problem Statement Graph Valid Tree LeetCode Solution – Given the edges of a graph, check if the edges make up a valid tree. If yes, return true and false otherwise. The edges are given as a 2D array of size n*2 Examples & Explanations Example 1: Input: n = 5, ...
Question 410. Spiral Matrix II Leetcode Solution Problem Statement This question Spiral Matrix II is very similar to Spiral Matrix Please try to attempt the above question to get a better idea before solving this problem. In this question, we are asked to generate a matrix of size n*n having elements in spiral order, and only n ...
Question 411. One Edit Distance LeetCode Solution Problem Statement One Edit Distance LeetCode Solution – Given two strings s and t, return true if they are both one edit distance apart, otherwise return false. A string s is said to be one distance apart from a string t if you can: Insert exactly one character into s to get t. Delete exactly one character from s to get t. Replace exactly one character of s with a different character to get t. Input: ...
Question 412. Brick Wall LeetCode Solution Problem Statement Brick Wall LeetCode Solution – There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the ...
Question 413. Integer Break LeetCode Solution Problem Statement Integer Break LeetCode Solution – Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. We need to Return the maximum product we can get. Input: n = 2 Output: 1 Explanation: 2 = 1 + 1, ...
Question 414. Path With Maximum Minimum Value LeetCode Solution Problem Statement Path With Maximum Minimum Value LeetCode Solution – Given an m x n integer matrix grid, return the maximum score of a path starting at (0, 0) and ending at (m - 1, n - 1) moving in the 4 cardinal directions. The score of a path is the minimum value in that path. For example, the score of ...
Question 415. Symmetric Tree LeetCode Solution Leetcode Solution Problem Statement The Symmetric Tree LeetCode Solution – “Symmetric Tree” states that given the root of the binary tree and we need to check if the given binary tree is a mirror of itself(symmetric around its center) or not? If Yes, we need to return true otherwise, false. Example: ...
Question 416. Jump Game Leetcode Solution Problem Statement Jump Game Leetcode Solution – You are given an integer array nums. You are initially positioned at the array’s first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. Example: Input 1: nums = [2, ...
Question 417. Spiral Matrix III LeetCode Solution Problem Statement Spiral Matrix III LeetCode Solution – You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral ...
Question 418. Linked List Cycle II LeetCode Solution Problem Statement Linked List Cycle II LeetCode Solution – Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously ...
Question 419. Maximum Number of Ways to Partition an Array LeetCode Solution Problem Statement Maximum Number of Ways to Partition an Array LeetCode Solution – You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions: 1 <= pivot < n nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot ...
Question 420. Bitwise AND of Numbers Range LeetCode Solution Problem Statement Bitwise AND of Numbers Range LeetCode Solution – Given 2 numbers left and right that represent the range [left, right], we have to find bitwise AND of all the numbers from left to right (both inclusive) Examples & Explanation Example 1: Input: left = 5, right = 7 ...
Question 421. Word Pattern LeetCode Solution Problem Statement Word Pattern LeetCode Solution – We are given 2 strings – “s” and “pattern”, we need to find if the pattern follows s. Follows here means full match. More formally, we can for every pattern[i] there should only be one s[i] and vice versa i.e. there is a ...
Question 422. Minimum Time to Collect All Apples in a Tree LeetCode Solution Problem Statement Minimum Time to Collect All Apples in a Tree LeetCode Solution – Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to ...
Question 423. Maximum Product of Three Numbers LeetCode Solution Problem Statement Maximum Product of Three Numbers LeetCode Solution – We are given an array, the question asks us to calculate the maximum product of any 3 numbers. Examples Example 1: Input: nums = [1,2,3] Output: 6 Example 2: Input: nums = [1,2,3,4] Output: 24 Example 3: Input: nums = ...
Question 424. Excel Sheet Column Title LeetCode Solution Problem Statement Excel Sheet Column Title LeetCode Solution – We are given a column number (let’s call it colNum) and need to return its corresponding column title as it appears in an excel sheet For example A -> 1 B -> 2 C -> 3 … Z -> 26 AA ...
Question 425. Valid Perfect Square LeetCode Solution Problem Statement Valid Perfect Square LeetCode Solution – Given a positive integer num, write a function that returns True if num is a perfect square else False. Follow up: Do not use any built-in library function such as sqrt. Input: num = 16 Output: true Explanation A boundary for our solution is fixed. for any number ...
Question 426. Random Pick Index LeetCode Solution Problem Statement Random Pick Index LeetCode Solution- We are given a constructor of class “Solution” and a function “pick” of type int. We are required to implement the “Solution” class as Solution(int[] nums) Initializes the object with the array nums. int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple ...
Question 427. Strobogrammatic Number LeetCode Solution Problem Statement Strobogrammatic Number LeetCode Solution – Given a string num which represents an integer, return true if num is a strobogrammatic number. A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Example Test Case 1: Input: num = “69” Output: true Test Case 2: Input: num = “692” Output: false Explanation ...
Question 428. Merge Two Binary Trees LeetCode Solution Problem Statement Merge Two Binary Trees LeetCode Solution – You are given two binary trees root1 and root2. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into ...
Question 429. Subarray Product Less Than K LeetCode Solution Problem Statement Subarray Product Less Than K LeetCode Solution – Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. Example Test Case 1: Input: inputArr = [10, 5, 2, 6] k = 100 ...
Question 430. Repeated Substring Pattern LeetCode Solution Problem Statement Repeated Substring Pattern LeetCode Solution – Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Input: s = "abab" Output: true Explanation: It is the substring "ab" twice. Explanation The first char of ...
Question 431. Next Greater Element III LeetCode Solution Problem Statement The problem, Next Greater Element III LeetCode Solution states that you are given a positive integer n and you need to find the next greatest integer using the digits present in n only. If there does not exist any such integer, you need to print -1. Moreover, the new ...
Question 432. Binary Tree Longest Consecutive Sequence LeetCode Solution Problem Statement Binary Tree Longest Consecutive Sequence LeetCode Solution – Given the root of a binary tree, return the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along with the parent-child connections. The longest consecutive ...
Question 433. Perfect Squares LeetCode Solution Problem Statement The Perfect Squares LeetCode Solution – “Perfect Squares” states that given an integer n and you need to return the minimum number of perfect squares whose sum equals to n. Note that the same perfect square can be used multiple times. Example: Input: n = 12 Output: 3 Explanation: ...
Question 434. Edit Distance LeetCode Solution Problem Statement The problem Edit Distance LeetCode Solution states that you are given two strings word1 and word2 and you need to convert word1 into word2 in minimum operations. The operations that can be performed on the string are – Insert a character Delete a character Replace a character Examples Test Case ...
Question 435. Custom Sort String Leetcode Solution Problem Statement The Custom Sort String LeetCode Solution – “Custom Sort String” states that you’re given two strings order and s. All characters of string order are unique and they are sorted in the custom order. We need to permute the characters of s and such that the characters follow ...
Question 436. Least Number of Unique Integers after K Removals Leetcode Solution Problem Statement The Least Number of Unique Integers after K Removals LeetCode Solution – “Least Number of Unique Integers after K removals” states that you’re given an array of integers and an integer k. Find the least number of unique integers after removing exactly k elements. Example: Input: arr = [5,5,4], k = 1 Output: 1 Explanation: Since k ...
Question 437. Find All Duplicates in an Array LeetCode Solution Problem Statement The problem, Find All Duplicates in an Array LeetCode Solution states that you are given an array of size n containing elements in the range [1,n]. Each integer can appear either once or twice and you need to find all the elements that appear twice in the array. Examples ...
Question 438. Move Zeroes LeetCode Solution Problem Statement The problem, Move Zeroes LeetCode Solution states that you are given an array containing zero and non-zero elements and you need to move all the zeroes to the end of the array, maintaining the relative order of non-zero elements in the array. You also need to implement an in-place ...
Question 439. Single Number Leetcode Solution Problem Statement Single Number Leetcode Solution – We are given a non-empty array of integers and need to find an element that appears exactly once. It is given in the question that every element appears twice except for one. Example 1: Input: nums = [2,2,1] Output: 1 Example 2: Input: ...
Question 440. Number of Provinces Leetcode Solution Problem Statement Number of Provinces Leetcode Solution – We are given an adjacency matrix representation of a graph and need to find the number of provinces. Here province is a group of directly or indirectly connected cities and no other cities outside of the group. Example Example 1: Input: isConnected ...
Question 441. 01 Matrix LeetCode Solution Problem Statement In this problem 01 Matrix LeetCode Solution, we need to find the distance of the nearest 0 for each cell of the given matrix. The matrix consists only of 0’s and 1’s and the distance of any two adjacent cells is 1. Examples Example 1: Input: mat = ...
Question 442. Sort Characters By Frequency LeetCode Solution Problem Statement Sort Characters By Frequency LeetCode Solution – Given a string S, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them. Example for Sort Characters By ...
Question 443. Non-decreasing Array LeetCode Solution Problem Statement Non-decreasing Array LeetCode Solution – given array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element. We define an array is non-decreasing if nums[index ] <= nums[index +1] holds for every index (0-based) such that (0 <= index <= n-2). ...
Question 444. Longest Substring with At Most K Distinct Characters LeetCode Solution Problem Statement Longest Substring with At Most K Distinct Characters LeetCode Solution – Given a string S and an integer K, return the length of the longest substring of S that contains at most K distinct characters. Example: Test Case 1: Input: S = “bacc” K = 2 Output: 3 Test Case 2: Input: S = “ab” ...
Question 445. Factorial Trailing Zeroes LeetCode Solution Problem Statement Factorial Trailing Zeroes LeetCode Solution – Given an integer n, return the number of trailing zeroes in n!. Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1. Input: n = 3 Output: 0 Explanation: 3! = 6, no trailing ...
Question 446. Convert Sorted Array to Binary Search Tree LeetCode Solutions Problem Statement Convert Sorted Array to Binary Search Tree LeetCode Solutions says given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more ...
Question 447. Word Ladder LeetCode Solution Problem Statement The Word Ladder LeetCode Solution – “Word Ladder” states that you are given a string beginWord, string endWord, and a wordList. We need to find the shortest transformation sequence length (if no path exists, print 0) from beginWord to endWord following the given conditions: All the Intermediate Words should ...
Question 448. Best Meeting Point LeetCode Solution Problem Statement The Best Meeting Point LeetCode Solution says Given a binary grid grid of size m x n where each 1 determines the home of one friend, we want to return the minimal total travel distance where the total travel distance is the sum of the distances between the houses of ...
Question 449. Longest Substring with At Least K Repeating Characters LeetCode Solution Problem Statement The problem Longest Substring with At Least K Repeating Characters LeetCode Solution says given a string S and an integer k, return the length of the longest substring of S such that the frequency of each character in this substring is greater than or equal to k. Example for Longest Substring with At Least ...
Question 450. Same Tree LeetCode Solution Problem Statement The problem Same Tree says Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Example: Test Case ...
Question 451. Spiral Matrix LeetCode Solution Problem Statement Spiral Matrix Problem says In Spiral Matrix we want to print all the elements of a matrix in a spiral form in the clockwise direction. Approach for Spiral Matrix: Idea The problem can be implemented by dividing the matrix into loops and printing all the elements in each ...
Question 452. Remove Duplicates from Sorted Array Leetcode Solution Problem Statement The Remove Duplicates from Sorted Array Leetcode Solution – says that you’re given an integer array sorted in non-decreasing order. We need to remove all duplicate elements and modify the original array such that the relative order of distinct elements remains the same and, report the value of ...
Question 453. Largest BST Subtree LeetCode Solution Problem Statement The Largest BST Subtree LeetCode Solution problem says given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree having the largest number of nodes. Note: A subtree must include all of its descendants. In a Binary ...
Question 454. My Calendar I LeetCode Solution Problem Statement My Calendar I LeetCode Solution – We need to write a program that can be used as a Calendar. We can add a new event if adding the event will not cause a double booking. A double booking happens when two events have some non-empty intersection (i.e., some moment is ...
Question 455. Sort Array By Parity LeetCode Solution Problem Statement The Sort Array By Parity LeetCode Solution – “Sort Array By Parity” states that you are given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Note: Return any array that satisfies this condition. Example: Input: Output: ...
Question 456. Remove Nth Node From End of List Leetcode Solution Problem Statement The Remove Nth Node From End of List Leetcode Solution – states that you are given the head of a linked list and you need to remove the nth node from the end of this list. After deleting this node, return the head of the modified list. Example: Input: ...
Question 457. Bulb Switcher LeetCode Solution Problem Statement Bulb Switcher LeetCode Solution – There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. In the third round, you toggle every third bulb (turning on if it’s off or turning off if it’s on). For the ith round, you ...
Question 458. Meeting Rooms II LeetCode Solution Problem Statement The Meeting Rooms II LeetCode Solution – “Meeting Rooms II” states that you are given an array of meeting time intervals “intervals” where “intervals[i] = [ start[i], end[i] ]”, return the minimum number of conference rooms required. Example: intervals = [[0,30],[5,10],[15,20]] 2 Explanation: Meeting one can be done ...
Question 459. Subarray Sum Equals K LeetCode Solution Problem Statement The Subarray Sum Equals K LeetCode Solution – “Subarray Sum Equals K” states that you are given an array of integers “nums” and an integer ‘k’, return the total number of continuous subarrays whose sum equals to ‘k’. Example: nums = [1, 2, 3], k=3 2 Explanation: There ...
Question 460. Longest Palindromic Substring LeetCode Solution Problem Statement The Longest Palindromic Substring LeetCode Solution – “Longest Palindromic Substring” states that You are Given a string s, return the longest palindromic substring in s. Note: A palindrome is a word that reads the same backward as forwards, e.g. madam. Example: s = "babad" "bab" Explanation: All ...
Question 461. Best Time to Buy and Sell Stock LeetCode Solution Problem Statement The Best Time to Buy and Sell Stock LeetCode Solution – “Best Time to Buy and Sell Stock” states that You are given an array of prices where prices[i] is the price of a given stock on an ith day. You want to maximize your profit by choosing ...
Question 462. Median of Two Sorted Arrays LeetCode Solution Problem statement Median of Two Sorted Arrays LeetCode solution – In the problem “Median of Two Sorted Arrays”, we are given two sorted arrays nums1 and nums2 of size m and n respectively, and we have to return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example nums1 = [1,3], ...
Question 463. Number of Islands LeetCode Solution Problem Statement The number of Islands LeetCode Solution – “Number of Islands” states that you are given an m x n 2D binary grid which represents a map of ‘1’s (land) and ‘0’s (water), you have to return the number of islands. An island is surrounded by water and is ...
Question 464. LRU Cache LeetCode Solution Question Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to ...
Question 465. 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 466. 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 467. 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 468. 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 469. 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 470. 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 471. 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 472. 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 473. 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 474. 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 475. 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 476. 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 477. 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 478. 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 479. 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 480. 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 481. 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 482. 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 483. 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 484. 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 485. 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 486. 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 487. 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 488. 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 489. 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 490. 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 491. 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 492. 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 493. 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 494. 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 495. 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 496. 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 497. 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 498. 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 499. 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 500. 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 501. 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 502. 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 503. 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 504. 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 505. 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 506. 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 507. 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 508. 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 509. 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 510. 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 511. 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 512. 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 ...