**Google LLC** is an American multinational technology company that focuses on search engine technology, online advertising, cloud computing, computer software, quantum computing, e-commerce, artificial intelligence, and consumer electronics. It has been referred to as the “most powerful company in the world” and one of the world’s most valuable brands due to its market dominance, data collection, and technological advantages in the area of artificial intelligence. ^{}It is considered one of the Big Five American information technology companies, alongside Amazon, Apple, Meta, and Microsoft.

It has got a 4.5* rating on Glassdoor and is considered one of the best product-based companies. It is highly regarded for its work-life balance. It is the best company to work for.

They provide good training as well which will be beneficial in future too. You can practice the below Google Interview Questions for the interview. We have collected past frequently asked Google Interview Questions for your reference.

Categories of Questions

## Google Array Questions

**Question 1. Remove All Ones With Row and Column Flips Leetcode Solution** Problem Statement: Remove All Ones With Row and Column Flips Leetcode Solution – You are given an m x n binary matrix grid. In one operation, you can choose any row or column and flip each value in that row or column (i.e., changing all 0‘s to 1‘s, and all 1‘s to 0‘s). Return true if it is possible to ...

**Question 2. 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 3. Maximum Side Length of a Square with Sum Less than or Equal to Threshold LeetCode Solution** Problem Statement “Maximum Side Length of a Square with Sum Less than or Equal to Threshold,” says that a m x n matrix mat and an integer threshold are given, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square. Example 1: Input: ...

**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. 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 7. Jump Game IV LeetCode Solution** Problem Statement: Jump Game IV LeetCode Solution says – Given an array of integers arr, you are initially positioned at the first index of the array. In one step you can jump from the index i to index: i + 1 where: i + 1 < arr.length. i - 1 where: i - 1 >= ...

**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. Min Cost Climbing Stairs LeetCode Solution** Problem Statement Min Cost Climbing Stairs LeetCode Solution – An integer array cost is given, where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with ...

**Question 13. 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 14. Find the Town Judge LeetCode Solution** Problem Statement: Find the Town Judge LeetCode Solution – In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge and we need to find the town judge. If the town judge exists, then: The town judge trusts nobody. ...

**Question 15. 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 16. Concatenation of Array LeetCode Solution** Problem Description: The Concatenation of Array Leetcode Solution: states that Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans. Let’s first try to understand the problem and what it states. The problem ...

**Question 17. Sliding Window Median Leetcode Solution** Problem Statement The Sliding Window Median LeetCode Solution – “Sliding Window Median” states that given an integer array nums and an integer k, where k is the sliding window size. We need to return the median array of each window of size k. Example: Input: [1,3,-1,-3,5,3,6,7], k = 3 Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000] Explanation: Median ...

**Question 18. 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 19. Bus Routes Leetcode Solution** Problem Statement The Bus Routes LeetCode Solution – “Bus Routes” states that you’re given an array of routes where routes[i] is a bus route such that ith bus repeats the route forever. We’ll be given a bus stop source and we want to reach the bus stop target. We can ...

**Question 20. Subarrays with K Different Integers Leetcode Solution** Problem Statement The Subarrays with K Different Integers LeetCode Solution – “Subarrays with K Different Integers” states that you’re given an integer array nums and an integer k. We need to find a total number of good subarrays of nums. A good array is defined as an array with exactly ...

**Question 21. 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 22. 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 23. 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 24. Maximum Profit in Job Scheduling Leetcode Solution** Problem Statement The Maximum Profit in Job Scheduling LeetCode Solution – “Maximum Profit in Job Scheduling” states that you’re given n jobs where each job starts from startTime[i] and ends at endTime[i] and obtaining the profit of profit[i]. We need to return the maximum profit that we can have such ...

**Question 25. 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 26. 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 27. 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 28. 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 29. 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 30. 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 31. 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 32. 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 33. Shortest Word Distance Leetcode Solution** Problem Statement The Shortest Word Distance LeetCode Solution – says that you’re given an array of strings and two different words. We need to return the shortest distance between these two words that appear in the input string. Example: Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" Output: 3 Explanation: Word “coding” occurs at position 4. ...

**Question 34. 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 35. 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 36. Design a Stack With Increment Operation Leetcode Solution** Problem Statement The Design a Stack With Increment Operation Leetcode Solution – states that we need to design a stack that supports the below operations efficiently. Assign the maximum capacity of the stack. Perform the push operation efficiently, if the size of the stack is strictly less than the maximum capacity of ...

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

**Question 38. 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 39. 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 40. 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 41. 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 42. 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 43. 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 44. Decompress Run-Length Encoded List Leetcode Solution** The problem Decompress Run-Length Encoded List Leetcode Solution states that you are given an array or vector containing a sequence. The sequence has some specific representation. The input sequence is formed from another sequence. We will call that another sequence as the original sequence. As per which the input sequence ...

**Question 45. Distance Between Bus Stops Leetcode Solution** The problem Distance Between Bus Stops Leetcode Solution provides us an array of integers describing the distance between the adjacent cities. The cities are given in a circular order. So, the last city is followed by the first city. Now, we are required to find out the minimum distance between ...

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

**Question 47. Compare Strings by Frequency of the Smallest Character Leetcode Solution** The problem Compare Strings by Frequency of the Smallest Character Leetcode Solution, states that we define a function f(s) over a non-empty string s such that f(s) is equal to the frequency of the smallest character in the string. Then we are given some words and some queries. for each ...

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

**Question 49. 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 50. 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 51. Relative Sort Array Leetcode Solution** In this problem, we are given two arrays of positive integers. All elements of the second array are distinct and are present in the first array. However, the first array can contain duplicate elements or elements that are not in the second array. We need to sort the first array ...

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

**Question 55. 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 56. 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 57. Special Array With X Elements Greater Than or Equal X Leetcode Solution** In the problem, “Special Array With X Elements Greater Than or Equal X”, we are given an array of non-negative integers. We need to find some integer X such that there are exactly X elements greater than or equal to it in the array. If there is no possible X ...

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

**Question 59. 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 60. Check If N and Its Double Exist Leetcode Solution** Problem statement In the problem ” Check If N and Its Double Exist” we are given an array of n elements. Array length is greater than or equal to two. Our task is to check if there exists a pair in the array such that the first value is double ...

**Question 61. Special Positions in a Binary Matrix Leetcode Solution** Problem Statement In Special Positions in a Binary Matrix problem a matrix of size n*m is given in which there are only two type of values 1s and 0s. A cell position is called special if value of that cell is 1 and values in all the cells in that ...

**Question 62. Mean of Array After Removing Some Elements Leetcode Solution** Problem statement In the problem ” Mean of Array After Removing Some Elements” we are given an array. All the elements of the array are positive integers. The size of the array is multiple of 20. Our task is to find the mean of the array excluding the smallest 5% ...

**Question 63. 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 64. Smallest Subarray with k Distinct Numbers** Suppose, you have an integer array and a number k. The problem statement asks to find out the smallest sub-array of range (l, r) inclusively, in such a way there are exactly k distinct numbers present in that smallest sub-array. Example Input: {1, 2, 2, 3, 4, 5, 5} k=3 ...

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

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

**Question 67. Queries on Probability of Even or Odd Number in given Ranges** We have given an array of integer, q number of queries. Where each query contains three integers, which defines a type of query. This means if we have given 0 it means we have to find the probability of choosing an odd number in the given range. Where the range ...

**Question 68. Range Minimum Query (Square Root Decomposition and Sparse Table)** In the range minimum query problem we have given a query and an integer array. Each query contains the range as left and right indexes for each range. The given task is to determine the minimum of all number that lies within the range. Example Input: arr[] = {2, 5, ...

**Question 69. 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 70. Queries for Decimal Values of Subarrays of a Binary Array** Write Queries for decimal values of subarrays of a binary array in a given binary array. The problem statement asks to find out the decimal number so formed with the help of range in a binary array. Example Input: arr[] = {1, 0, 1, 1, 0, 0, 1, 1} Query(1, ...

**Question 71. 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 72. Print all triplets in sorted array that form AP** The problem “Print all triplets in sorted array that form AP” states that we have given a sorted integer array. The task is to find out all the possible triplets that can form an Arithmetic Progression. Example arr[] = {1,3,5,7,8,12,15,16,20,30} (1, 3, 5), (3, 5, 7), (1, 8, 15), (8, ...

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

**Question 75. Find all triplets with zero sum** The problem “Find all triplets with zero sum” states that you are given an array containing positive and negative number both. The problem statement asks to find out the triplet with the sum equal to 0. Example arr[] = {0,-2,1,3,2,-1} (-2 -1 3) (-2 0 2) (-1 0 1) Explanation ...

**Question 76. Maximum Distance in Array** The problem “Maximum Distance in Array” states that you are given “n” no. of arrays and all the arrays are given in ascending order. Your task is to find the maximum difference/absolute difference of two numbers in an array and we can define the maximum distance between two numbers as ...

**Question 77. Range Queries for Longest Correct Bracket Subsequence** You are given a sequence of some brackets subsequence, in other words, you are given brackets like ‘(’ and ‘)’ and you are given a query range as a starting point and ending point. The problem “Range Queries for Longest Correct Bracket Subsequence” asks to find out the maximum length ...

**Question 78. Print modified array after multiple array range increment operations** The problem “Print modified array after multiple array range increment operations” states that you are given an integer array and ‘q’ numbers of queries are given. One integer value “d” is also given. Each query contains two integers, starting value and an ending value. The problem statement asks to find ...

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

**Question 80. Array Queries for multiply replacements and product** The problem “Array Queries for multiply, replacements and product” states that you are given an array of integer and there will be three types of queries, where you have to solve the following type of queries: Type 1: There will be three values left, right and a number X.In this ...

**Question 81. Difference Array | Range update query in O(1)** You are given an integer array and two types of queries, one is to add a given number in a range and the other to print the whole array. The problem “Difference Array | Range update query in O(1)” requires us to perform the range updates in O(1). Example arr[] ...

**Question 82. 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 83. Binary array after M range toggle operations** You are given a binary array, which consists of 0 initially and Q number of queries. The problem statement asks to toggle the values (converting 0s into 1s and 1s into 0s). After the Q queries performed, print the resultant array. Example arr[] = {0, 0, 0, 0, 0} Toggle(2,4) ...

**Question 84. Constant time range add operation on an array** You have given an integer array and initially, it was initialized as 0 and also given a range. The task is to add the given number in the range of the array and print the resultant array. Example arr[] = {0, 0, 0, 0, 0} Query: {(0, 2, 50), (3, ...

**Question 85. Range LCM Queries** Problem Statement The problem “Range LCM Queries” states that you have an integer array and q number of queries. Each query contains the (left, right) as a range. The given task is to find out the LCM(left, right), i.e, LCM of all the number that comes in the range of ...

**Question 86. Queries on XOR of greatest odd divisor of the range** Problem Statement The problem “Queries on XOR of greatest odd divisor of the range” states that you are given an array of integer and query q, each query consists of a range. The problem statement asks to find out the XOR of the greatest odd divisor within the given range ...

**Question 87. Queries for counts of array elements with values in given range** Problem Statement The problem “Queries for counts of array elements with values in given range” states that you have an integer array and two number x and y. The problem statement asks to find out the count of numbers present in array that lies between the given x and y. ...

**Question 88. Number of elements less than or equal to a given number in a given subarray** Problem Statement The problem “Number of elements less than or equal to a given number in a given subarray” states that you are given an integer array and q number of queries. There will be two types of queries à queryUpdate(i, v): There will be two integers i and v, ...

**Question 89. Queries for GCD of all numbers of an array except elements in a given range** Problem Statement The “Queries for GCD of all numbers of an array except elements in a given range” problem states that you will be given an integer array and a q number of queries. Each query contains the number left and right. The problem statement asks to find out the ...

**Question 90. Products of ranges in an array** Problem Statement The problem “Products of ranges in an array” states that you are given an integer array consisting of numbers range from 1 to n and q number of queries. Each query contains the range. The problem statement asks to find out the product within the given range under ...

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

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

**Question 93. 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 94. 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 95. Sum of minimum and maximum elements of all subarrays of size k** Problem Statement The problem “Sum of minimum and maximum elements of all subarrays of size k” states that you are given an array containing positive and negative integers, find the sum of minimum and maximum elements of all the sub-arrays of size k. Examples arr[] = {5, 9, 8, 3, ...

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

**Question 97. 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 98. 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 99. Collect maximum points in a grid using two traversals** Problem Statement We are given a matrix of size “n x m”, and we need to collect maximum points in a grid using two traversals. If we are standing at cell i,j then we have three options to go to cell i+1, j or i+1, j-1or i+1, j+1. That is ...

**Question 100. 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 101. Matrix Chain Multiplication** In the matrix chain multiplication II problem, we have given the dimensions of matrices, find the order of their multiplication such that the number of operations involved in multiplication of all the matrices is minimized. Consider you have 3 matrices A, B, C of sizes a x b, b x ...

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

**Question 103. 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 104. 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 105. 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 106. K Empty Slots** K empty slots correctly present a gardener’s dilemma, trying to pick flowers that suit our condition. Our gardener has a field of N-slots. Mr gardener has planted a flower in each one of the slots. Each flower will bloom on a certain unique day. Also, we have planted evergreen flowers. ...

**Question 107. 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 108. 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 109. 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 110. 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 111. 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 112. 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 113. 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 114. 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 115. Find The Duplicate Number** Given an array nums containing (n + 1) elements and every element is between 1 to n. If there is only one duplicate element, find the duplicate number. Examples Input: nums = {1, 3, 4, 2, 2} Output: 2 Input: nums = {3, 1, 3, 4, 2} Output: 3 Naive ...

**Question 116. 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 117. Find the Duplicate Element** Given an array of integers of size n+1 where each element of the array is between 1 and n (inclusive), there is one duplicate element in the array, find the duplicate element. Brute force method – Approach 1 for Find the Duplicate Element For every ith element run a loop ...

**Question 118. K Empty Slots LeetCode** K Empty Slots is a very famous problem on LeetCode. The problem statement is like that- A garden is consists of n slots containing a flower each. All the flowers are unbloomed initially. Given an array a[ ] of flowers and an integer k. Considering i stating from 0, i+1’th ...

**Question 119. 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 120. 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 121. 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 122. 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 123. 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 124. 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 125. 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 126. 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 127. Pascal Triangle Leetcode** The Pascal Triangle is a very good Leetcode problem that is asked so many times in Amazon, Microsoft, and other companies. we have given non-negative integer rows, print first rows rows of the pascal triangle. Example rows = 5 rows = 6 Types of solution for Pascal Triangle Leetcode Dynamic Programming ...

**Question 128. 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 129. 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 130. 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 131. Merge K Sorted Arrays and Print Sorted Output** Problem Statement In the “Merge K Sorted Arrays and Print Sorted Output” problem we have given k sorted arrays of different size. Write a program to merge those arrays and prints the final sorted array as output. Input Format The first line containing an integer n. Next n lines containing ...

**Question 132. 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 133. 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 134. 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 135. 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 136. 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 137. 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 138. Find the two Numbers with Odd Occurrences in an Unsorted Array** Problem Statement In the “Find the two Numbers with Odd Occurrences in an Unsorted Array” problem we have given an unsorted array. In this array other than two numbers all other numbers occur even number of times. Find the two numbers that occur an odd number of times. Note: The ...

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

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

**Question 142. 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 143. 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 144. 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 145. 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 146. Four Elements that Sum to Given** Problem Statement In four elements that sum to a given problem, we have given an array containing N elements that may be positive or negative. Find the set of four elements whose sum is equal to given value k. Input Format First-line containing an integer N. Second-line containing an array ...

**Question 147. 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 148. 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 149. 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 150. 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 151. 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 152. 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 153. 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 154. 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 155. 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 156. Reorder Array Using Given Indexes** Problem Statement In recorder array using given indexes problem we have given two input arrays of the same size, the second array is index array, we need to reorder elements in the same array according to given index array. Example Input array : [4, 2, 1, 3] index : [3, ...

**Question 157. 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 158. 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 159. Reorder an Array According to the Given Indexes** Problem Statement Given an input array and the array of indexes, reorder an array according to the given indexes. Here we have to arrange the elements according to the indexes as per the given index array. Example Input : arr[] = [23,24,25] and given indexes are index[] = [1,0,2] 23 ...

**Question 160. 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 161. 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 162. Check if the Elements of an Array are Consecutive** Problem Statement Given an array, Check if the elements of an array are consecutive. Here, consecutive elements mean, when we take all the elements in the array they need to form a consecutive sequence. Example Input arr[]={65,68,66,64,67} Output array contains consecutive elements here, all the elements in the array are ...

**Question 163. 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 164. 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 165. Find K Length Subarray of Maximum Average** Problem Statement In find K length subarray of maximum average problem, we have given an array of size N. Finding the start position of a subarray in the given array of size k with a maximum average. The array may contain positive and negative numbers. (Average = sum of elements/number ...

**Question 166. 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 167. 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 168. 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 169. 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 170. 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 171. 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 172. 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 173. 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 174. 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 ...

## Google String Questions

**Question 175. Camelcase Matching Leetcode Solution** Problem Statement: Camelcase Matching Leetcode Solution says that – Given an array of string “queries” and string “pattern”, return boolean array result where result[i] is true where “queries[i]” matches with “pattern”, false otherwise. A query word “queries[i]” matches with “pattern” if you can insert some lowercase English letters in “pattern” so ...

**Question 176. 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 177. Rotate String LeetCode Solution** Problem Statement Rotate String LeetCode Solution – Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s. A shift on s consists of moving the leftmost character of s to the rightmost position. For example, if s = “abcde”, then it will ...

**Question 178. 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 179. 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 180. Detect Capital Leetcode Solution** Problem Statement: Detect Capital Leetcode Solution says that – Given a string, return true if the usage of capitals in it is right. The conditions for the right words are : All letters in this word are capitals, like "UK". All letters in this word are not capitals, like "going". Only ...

**Question 181. 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 182. 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 183. 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 184. 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 185. 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 186. 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 187. 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 188. 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 189. 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 190. 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 191. 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 192. 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 193. Shortest Word Distance Leetcode Solution** Problem Statement The Shortest Word Distance LeetCode Solution – says that you’re given an array of strings and two different words. We need to return the shortest distance between these two words that appear in the input string. Example: Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" Output: 3 Explanation: Word “coding” occurs at position 4. ...

**Question 194. 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 195. License Key Formatting Leetcode Solution** Problem Statement In the problem “License Key Formatting”, the input consists of a string of characters, representing a license key. Initially, the string is separated into N + 1 groups(words) by N dashes in between. We are also given an integer K, and the goal is to format the string ...

**Question 196. 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 197. Rearrange Spaces Between Words Leetcode Solution** Problem Statement In this problem, we are given a text string having some number of words that are placed among the spaces. Words can have only lowercase english letters. Ofcourse each words are separated with at least one space. Also The text has at least one word. e.g. text= ” ...

**Question 198. Maximum Score After Splitting a String Leetcode Solution** The problem Maximum Score After Splitting a String Leetcode Solution provided us with a string. The given string contains only 0 and 1. So one can also consider it as a binary sequence. The problem then asked us to find the maximum score achievable after splitting the string. After splitting ...

**Question 199. 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 200. Compare Strings by Frequency of the Smallest Character Leetcode Solution** The problem Compare Strings by Frequency of the Smallest Character Leetcode Solution, states that we define a function f(s) over a non-empty string s such that f(s) is equal to the frequency of the smallest character in the string. Then we are given some words and some queries. for each ...

**Question 201. To Lower Case Leetcode Solution** The problem To Lower Case Leetcode Solution provides us with a string and asks us to convert all the upper case alphabets into lower case alphabets. We are required to convert all the upper case or lower case alphabets into lower case characters. So, the problem seems simple but before ...

**Question 202. Student Attendance Record I Leetcode Solution** Problem statement In the problem ” Student Attendance Record I” we are given a string where each letter represents the attendance detail of a student. The interpretation of letters in the string is as follows: ‘A’ means absent. ‘P’ means present. ‘L’ means late The student will be rewarded based ...

**Question 203. Find the Difference Leetcode Solution** In this problem, we are given two strings. The second string is generated by shuffling the characters of the first string randomly and then adding an extra character at any random position. We need to return the extra character that was added to the second string. The characters will always ...

**Question 204. 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 205. 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 206. 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 207. 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 208. Make The String Great Leetcode Solution** Problem Statement In “Make The String Great” problem a string is given consists of lower and upper case letters. We have to make this string good by removing adjacent characters in the string which is making the string bad. A good string is a string which doesn’t have two adjacent ...

**Question 209. Length of Last Word Leetcode Solution** Problem Statement In this problem a multiword string is given and we have to return the length of the last word present in that string. If there are no words we have to return 0. Example s = "Hello World" 5 Explanation: Length of the last word “World” is 5. ...

**Question 210. 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 211. Find Smallest Range Containing Elements from k Lists** In the problem “Find the smallest range containing elements from k lists” we have given K lists which are sorted and of the same size N. It asks to determine the smallest range that contains at least element(s) from each of the K lists. If there is more than one ...

**Question 212. Smallest Good Base** Problem Statement Suppose we have given an integer n, for all the values of n base k are 1 when a good base k>=2. Suppose we have given a string format-number ‘n’. The problem statement asks to find out the smallest good base of n and to return it in ...

**Question 213. Minimum insertions to form a palindrome with permutations allowed** The problem “Minimum insertions to form a palindrome with permutations allowed” states that you are given a String with all letters in lowercase. The problem statement asks to find out the minimum insertion of a character to a string that it can become Palindrome. The position of characters can be ...

**Question 214. LCS (Longest Common Subsequence) of three strings** The problem “LCS (Longest Common Subsequence) of three strings” states that you are given 3 strings. Find out the longest common subsequence of these 3 strings. LCS is the string that is common among the 3 strings and is made of characters having the same order in all of the ...

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

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

**Question 224. 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 225. 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 226. Repeated Substring Pattern** In repeated substring patterns we have given a string check if it can be constructed by taking a substring of itself and appending multiple copies of the substring together. Example Input 1: str = “abcabcabc” Output: True Explanation: “abcabcabc” can be formed by repeatedly appending “abc” to an empty string. ...

**Question 227. 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 228. 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 229. 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 230. 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 231. 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 232. 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 233. 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 234. 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 235. Guess The Word** Guess The Word is an interactive problem. An interactive problem means the data which is given to us is not predetermined. We can print values or call the specific function to interact or get more information regarding the solution. After each step, we also need to FLUSH the buffer to ...

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

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

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

**Question 241. 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 242. 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 243. 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 244. Longest Common Prefix using Divide and Conquer** Problem Statement In the “Longest Common Prefix using Divide and Conquer ” problem, we have given an integer n and n strings. Write a program that will print the longest common prefix. If there is no common prefix then print “-1”. Input Format The first line contains an integer n. ...

**Question 245. Lower Case To Upper Case** Problem Statement In the “Lower Case To Upper Case” problem, we have given a string “s” with only lower case letters. Write a program that will print the same string but with upper case letters. Input Format The first and only one line containing a string “s”. Output Format The ...

**Question 246. 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 247. 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 248. 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 249. 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 250. 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 ...

## Google Tree Questions

**Question 251. 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 252. 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 253. 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 254. 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 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. 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 257. 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 258. 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 259. 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 260. Recover Binary Search Tree Leetcode Solution** Problem Statement The Recover Binary Search Tree LeetCode Solution – “Recover Binary Search Tree” states that given the root of the binary search tree, where the values of exactly two nodes are swapped by mistake. We need to recover the tree without changing its structure. Example: Input: root = [1,3,null,null,2] Output: [3,1,null,null,2] ...

**Question 261. 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 262. Minimum Distance Between BST Nodes Leetcode Solution** The problem Minimum Distance Between BST Nodes Leetcode Solution states that you are provided with a Binary Search Tree. And you are required to find the minimum difference in the entire BST. So, you need to find the minimum absolute difference between any two nodes in the BST. A BST ...

**Question 263. Minimum Absolute Difference in BST Leetcode Solution** The problem Minimum Absolute Difference in BST Leetcode Solution states that you are provided with a Binary Search Tree. And you are required to find the minimum absolute difference in the entire BST. A BST or a Binary Search Tree is nothing but a tree with some nodes that follow ...

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

**Question 265. 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 266. Kth ancestor of a node in binary tree** Problem Statement The problem “Kth ancestor of a node in binary tree” states that you are given a binary tree and a node. Now we need to find the kth ancestor of this node. An ancestor of any node is the nodes that lie on the path from the root ...

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

**Question 268. Range LCM Queries** Problem Statement The problem “Range LCM Queries” states that you have an integer array and q number of queries. Each query contains the (left, right) as a range. The given task is to find out the LCM(left, right), i.e, LCM of all the number that comes in the range of ...

**Question 269. Number of elements less than or equal to a given number in a given subarray** Problem Statement The problem “Number of elements less than or equal to a given number in a given subarray” states that you are given an integer array and q number of queries. There will be two types of queries à queryUpdate(i, v): There will be two integers i and v, ...

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

**Question 272. Number of siblings of a given Node in n-ary Tree** Problem Statement The problem “Number of siblings of a given Node in n-ary Tree” states that you are given an n-ary Tree and a target node. Find the number of siblings of the target node. Assume that node is always present in the tree and the first node is the ...

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

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

**Question 275. K’th Largest Element in BST when modification to BST is not allowed** Problem Statement “K’th Largest Element in BST when modification to BST is not allowed” states that you are given a binary search tree and you need to find the kth largest element. This means that when all the elements of the binary search tree are arranged in descending order. Then ...

**Question 276. Iterative method to find ancestors of a given binary tree** Problem Statement “Iterative method to find ancestors of a given binary tree” problem states that you are given a binary tree and an integer representing a key. Create a function to print all the ancestors of the given key using iteration. Example Input key = 6 5 2 1 Explanation: ...

**Question 277. Height of a generic tree from parent array** Problem Statement “Height of a generic tree from parent array” problem states that you are given a tree with n vertices as an array par[0…n-1]. Here every index i in par[] represents a node and the value at i represents the immediate parent of that node. For the root node ...

**Question 278. Find k-th smallest element in BST (Order Statistics in BST)** Problem Statement “Find k-th smallest element in BST (Order Statistics in BST)” problem states that you are given a binary search tree and you need to find the k-th smallest number in the BST. This means if we do an in-order traversal of the binary search tree and store the ...

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

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

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

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

**Question 284. 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 285. Balanced Binary Tree** In the balanced binary tree problem, we have given the root of a binary tree. We have to determine whether or not it is height balance. Examples Input Output true Input Output: false Balanced Binary Tree Every node in a balanced binary tree has a difference of 1 or less ...

**Question 286. Interval Tree** In the interval tree problem, we have given a set of intervals and three types of queries addInterval(x,y): Add an interval (x,y) to the set removeInterval(x,y): Remove an interval (x,y) from the set checkInterval(x,y): Check if interval (x,y) overlaps with some existing interval Design a data structure( Interval Tree ) ...

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

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

**Question 290. Find Duplicate Subtrees** Duplicate Subtrees Subtrees are said to be duplicate if they have the same node values and structure. Given a binary tree with n nodes. Find all the duplicate subtrees and return their root node. Example Here, the subtrees 4 and 2->4 appear more than once therefore we will return root ...

**Question 291. 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 292. 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 293. Unique Binary Search Trees** Firstly we have to find the total number of counts to form a unique binary search tree. After it, we construct all possible unique BST. First of all, we have to know the construction of BST. In a Binary Search Tree, the nodes present in the left subtree wrt. any ...

**Question 294. Verify Preorder Serialization of a Binary Tree** First, we need to know what actually Preorder of a Binary Tree is. Preorder is a type of Binary Tree traversal. In this traversal first, we visit the node. After visiting traverse the left sub-tree first and then right sub-tree. Now, move to what we have to do in this ...

## Google Graph Questions

**Question 295. Most Stones Removed with Same Row or Column LeetCode Solution** Problem Statement Most Stones Removed with Same Row or Column LeetCode Solution says that On a 2D plane we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same ...

**Question 296. 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 297. Find the Town Judge LeetCode Solution** Problem Statement: Find the Town Judge LeetCode Solution – In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge and we need to find the town judge. If the town judge exists, then: The town judge trusts nobody. ...

**Question 298. Height of a generic tree from parent array** Problem Statement “Height of a generic tree from parent array” problem states that you are given a tree with n vertices as an array par[0…n-1]. Here every index i in par[] represents a node and the value at i represents the immediate parent of that node. For the root node ...

**Question 299. Iterative Depth First Traversal of Graph** In iterative depth first traversal of graph problem, we have given a graph data structure. Write the program to print the depth first traversal of the given graph using the iterative method. Example Input : 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 ...

**Question 300. 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 301. 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 302. 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 ...

## Google Stack Questions

**Question 303. 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 304. 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 305. 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 306. 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 307. 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 308. 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 309. 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 310. 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 311. Design a Stack With Increment Operation Leetcode Solution** Problem Statement The Design a Stack With Increment Operation Leetcode Solution – states that we need to design a stack that supports the below operations efficiently. Assign the maximum capacity of the stack. Perform the push operation efficiently, if the size of the stack is strictly less than the maximum capacity of ...

**Question 312. Build an Array With Stack Operations Leetcode Solution** The Build an Array With Stack Operations Leetcode Solution problem provides us with an integer sequence and an integer n. The problem states that we are given a sequence of integers from 1 to n. Then we use a stack to produce an integer sequence that is given to us ...

**Question 313. Make The String Great Leetcode Solution** Problem Statement In “Make The String Great” problem a string is given consists of lower and upper case letters. We have to make this string good by removing adjacent characters in the string which is making the string bad. A good string is a string which doesn’t have two adjacent ...

**Question 314. Range Queries for Longest Correct Bracket Subsequence** You are given a sequence of some brackets subsequence, in other words, you are given brackets like ‘(’ and ‘)’ and you are given a query range as a starting point and ending point. The problem “Range Queries for Longest Correct Bracket Subsequence” asks to find out the maximum length ...

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

**Question 316. Iterative method to find ancestors of a given binary tree** Problem Statement “Iterative method to find ancestors of a given binary tree” problem states that you are given a binary tree and an integer representing a key. Create a function to print all the ancestors of the given key using iteration. Example Input key = 6 5 2 1 Explanation: ...

**Question 317. Iterative Depth First Traversal of Graph** In iterative depth first traversal of graph problem, we have given a graph data structure. Write the program to print the depth first traversal of the given graph using the iterative method. Example Input : 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 ...

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

**Question 319. 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 320. 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 321. 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 322. Verify Preorder Serialization of a Binary Tree** First, we need to know what actually Preorder of a Binary Tree is. Preorder is a type of Binary Tree traversal. In this traversal first, we visit the node. After visiting traverse the left sub-tree first and then right sub-tree. Now, move to what we have to do in this ...

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

**Question 324. 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 325. 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 ...

## Google Queue Questions

**Question 326. Implementation of Deque using Doubly Linked List** Problem Statement The problem “Implementation of Deque using Doubly Linked List” states that you need to implement the following functions of Deque or Doubly Ended Queue using a doubly linked list, insertFront(x) : Add element x at the starting of Deque insertEnd(x) : Add element x at the end of ...

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

**Question 328. Sum of minimum and maximum elements of all subarrays of size k** Problem Statement The problem “Sum of minimum and maximum elements of all subarrays of size k” states that you are given an array containing positive and negative integers, find the sum of minimum and maximum elements of all the sub-arrays of size k. Examples arr[] = {5, 9, 8, 3, ...

**Question 329. Number of siblings of a given Node in n-ary Tree** Problem Statement The problem “Number of siblings of a given Node in n-ary Tree” states that you are given an n-ary Tree and a target node. Find the number of siblings of the target node. Assume that node is always present in the tree and the first node is the ...

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

**Question 331. Height of a generic tree from parent array** Problem Statement “Height of a generic tree from parent array” problem states that you are given a tree with n vertices as an array par[0…n-1]. Here every index i in par[] represents a node and the value at i represents the immediate parent of that node. For the root node ...

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

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

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

## Google Matrix Questions

**Question 335. Remove All Ones With Row and Column Flips Leetcode Solution** Problem Statement: Remove All Ones With Row and Column Flips Leetcode Solution – You are given an m x n binary matrix grid. In one operation, you can choose any row or column and flip each value in that row or column (i.e., changing all 0‘s to 1‘s, and all 1‘s to 0‘s). Return true if it is possible to ...

**Question 336. 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 337. 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 338. 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 339. 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 340. Special Positions in a Binary Matrix Leetcode Solution** Problem Statement In Special Positions in a Binary Matrix problem a matrix of size n*m is given in which there are only two type of values 1s and 0s. A cell position is called special if value of that cell is 1 and values in all the cells in that ...

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

**Question 342. Collect maximum points in a grid using two traversals** Problem Statement We are given a matrix of size “n x m”, and we need to collect maximum points in a grid using two traversals. If we are standing at cell i,j then we have three options to go to cell i+1, j or i+1, j-1or i+1, j+1. That is ...

**Question 343. 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 344. 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 345. Matrix Chain Multiplication** In the matrix chain multiplication II problem, we have given the dimensions of matrices, find the order of their multiplication such that the number of operations involved in multiplication of all the matrices is minimized. Consider you have 3 matrices A, B, C of sizes a x b, b x ...

**Question 346. 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 347. 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 348. 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 349. 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 350. 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 351. 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. ...

## Google Other Questions

**Question 352. Candy LeetCode Solution** Problem Statement: Candy LeetCode Solution: There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more ...

**Question 353. 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 354. 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 355. Validate Stack Sequences LeetCode Solution** Problem Statement Validate Stack Sequences LeetCode Solution – Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise. Example 1: Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: true Explanation: We ...

**Question 356. 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 357. 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 358. Single Element in a Sorted Array LeetCode Solution** Problem Statement: Single Element in a Sorted Array LeetCode Solution says that – You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once. Your solution must run in O(log n) time ...

**Question 359. 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 360. Fibonacci Number LeetCode Solution** Problem Statement: Fibonacci Number LeetCode Solution says 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 - 2), ...

**Question 361. All Possible Full Binary Trees LeetCode Solution** Problem Statement: All Possible Full Binary Trees LeetCode Solution : Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final ...

**Question 362. Stone Game IV LeetCode Solution** Problem Statement: Stone Game IV LeetCode Solution : Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player’s turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she ...

**Question 363. Trapping Rain Water II LeetCode Solution** Problem Statement: Trapping Rain Water II LeetCode Solution : Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining. Examples: Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] Output: 4 Explanation: After the rain, water is trapped between the ...

**Question 364. The Number of Weak Characters in the Game LeetCode Solution** Problem Statement: The Number of Weak Characters in the Game LeetCode Solution : You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game. A character is said ...

**Question 365. 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 366. Group Anagrams LeetCode Solution** Problem Statement Group Anagrams LeetCode Solution Says that – Given an array of strings strs, group the anagrams together. You can return the answer in any order. 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: ...

**Question 367. Sliding Window Maximum LeetCode Solution** Problem Statement Sliding Window Maximum LeetCode Solution Says that – You are given an array of integers nums, and there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time ...

**Question 368. Binary Search LeetCode Solution** Problem Statement Binary Search LeetCode Solution says that – Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [-1,0,3,5,9,12], target ...

**Question 369. Container With Most Water LeetCode Solution** Problem Statement Container With Most Water LeetCode Solution says that – You are given an integer array height of length n. There are n vertical lines are drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container ...

**Question 370. 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 371. Paint House LeetCode Solution** Problem Statement Paint House LeetCode Solution – There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no ...

**Question 372. Closest Binary Search Tree Value II LeetCode Solution** Problem Statement: Closest Binary Search Tree Value II LeetCode Solution: Given the root of a binary search tree, a target value, and an integer k, return the k values in the BST that are closest to the target. You may return the answer in any order. You are guaranteed to have only one unique set of k values in the BST that are closest ...

**Question 373. Sentence Screen Fitting LeetCode Solution** Problem Statement: Sentence Screen Fitting LeetCode Solution: Given a rows x cols screen and a sentence represented as a list of strings, return the number of times the given sentence can be fitted on the screen. The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A ...

**Question 374. 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 375. 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 376. 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 377. 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 378. Isomorphic Strings LeetCode Solution** Problem Statement Isomorphic Strings LeetCode Solution – Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the ...

**Question 379. 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 380. 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 381. 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 382. 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 383. 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 384. 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 385. 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 386. 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 387. 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 388. 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 389. 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 390. Find the Town Judge LeetCode Solution** Problem Statement: Find the Town Judge Leetcode Solution: In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. ...

**Question 391. Minimum Number of Operations to Move All Balls to Each Box LeetCode Solution** Problem Statement: Minimum Number of Operations to Move All Balls to Each Box LeetCode Solution: You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == ...

**Question 392. 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 393. 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 394. Stone Game IV LeetCode Solution** Problem Statement Stone Game IV LeetCode Solution – Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player’s turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she ...

**Question 395. 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 396. 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 397. 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 398. 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 399. 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 400. 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 401. 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 402. 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 403. 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 404. 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 405. Concatenation of Array LeetCode Solution** Problem Statement : Concatenation of Array LeetCode Solution – Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans. Example : Example 1 Input: nums = [1,2,1] Output: [1,2,1,1,2,1] Explanation: The array ...

**Question 406. 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 407. 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 408. 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 409. Decrease Elements To Make Array Zigzag LeetCode Solution** Problem Statement : Decrease Elements To Make Array Zigzag LeetCode Solution – Given an array nums of integers, a move consists of choosing any element and decreasing it by 1. An array A is a zigzag array if either: Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > … ...

**Question 410. 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 411. Count Submatrices With All Ones LeetCode Solution** Problem Statement Count Submatrices With All Ones LeetCode Solution – We are given an m x n binary matrix and are asked to return the number of submatrices that have all ones. Examples and Explanations Example 1: Input: mat = [[1,0,1],[1,1,0],[1,1,0]] Output: 13 Explanation: There are 6 rectangles of side ...

**Question 412. 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 413. 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 414. 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 415. 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 416. 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 417. Construct Binary Tree from Preorder and Postorder Traversal LeetCode Solution** Problem Statement Construct Binary Tree from Preorder and Postorder Traversal LeetCode Solution – Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree. If there exist multiple answers, you can return any of them. Input: preorder ...

**Question 418. Number of Dice Rolls With Target Sum LeetCode Solution** Problem Statement Number of Dice Rolls With Target Sum LeetCode Solution – You have n dice and each die has k faces numbered from 1 to k. Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be ...

**Question 419. Race Car LeetCode Solution** Problem Statement Race Car LeetCode Solution – Your car starts at the position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): When you get an instruction 'A', your car does the following: position += speed ...

**Question 420. 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 421. 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 422. 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 423. 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 424. 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 425. Design Browser History LeetCode Solution** Problem Statement Design Browser History LeetCode Solution – You have a browser with one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps. Implement the BrowserHistory class: BrowserHistory(string homepage) Initializes the object with the homepage of the ...

**Question 426. 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 427. 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 428. 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 429. 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 430. 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 431. 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 432. 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 433. Maximize Distance to Closest Person LeetCode Solution** Problem Statement Maximize Distance to Closest Person LeetCode Solution – You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed). There is at least one empty seat, and at least one person sitting. Alex wants to ...

**Question 434. 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 435. 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 436. 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 437. 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 438. 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 439. 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 440. 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 441. Reorder Data in Log Files LeetCode Solution** Problem Statement Reorder Data in Log Files LeetCode Solution – You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier. There are two types of logs: Letter-logs: All words (except the identifier) consist of lowercase English letters. Digit-logs: All words ...

**Question 442. 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 443. 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 444. Optimal Account Balancing LeetCode Solution** Problem Statement Optimal Account Balancing LeetCode Solution – You are given an array of transactions transactions where transactions[i] = [fromi, toi, amounti] indicates that the person with ID = fromi gave amounti $ to the person with ID = toi. Return the minimum number of transactions required to settle the debt. Input: transactions = [[0,1,10],[2,0,5]] Output: 2 Explanation: Person #0 ...

**Question 445. 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 446. 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 447. 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 448. Robot Bounded In Circle LeetCode Solution** Problem Statement Robot Bounded In Circle LeetCode Solution – On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that: The north direction is the positive direction of the y-axis. The south direction is the negative direction of the y-axis. The east direction is the positive direction of the x-axis. The west direction is the ...

**Question 449. 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 450. 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 451. 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 452. 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 453. Snakes and Ladders LeetCode Solution** Problem Statement Snakes and Ladders LeetCode Solution – You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating directions in each row. You start on the square 1 of the board. In each move, ...

**Question 454. Arithmetic Slices II – Subsequence LeetCode Solution** Problem Statement : Arithmetic Slices II – Subsequence LeetCode Solution – Given an integer array of nums, return the number of all the arithmetic subsequences of nums. A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For ...

**Question 455. 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 456. 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 457. Flatten 2D Vector LeetCode Solution** Problem Statement Flatten 2D Vector LeetCode Solution – Design an iterator to flatten a 2D vector. It should support the next and hasNext operations. Implement the Vector2D class: Vector2D(int[][] vec) initializes the object with the 2D vector vec. next() returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all ...

**Question 458. 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 459. 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 460. 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 461. 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 462. 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 463. 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 464. 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 465. 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 466. 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 467. 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 468. 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 469. 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 470. 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 471. 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 472. Parallel Courses II LeetCode Solution** Problem Statement Parallel Courses II LeetCode Solution- You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei have to be taken before the course nextCoursei. Also, you are given the ...

**Question 473. 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 474. 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 475. The Maze III LeetCode Solution** Problem Statement The Maze III LeetCode Solution – There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won’t stop rolling until hitting a wall. When the ball stops, ...

**Question 476. 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 477. 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 478. 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 479. Find if Path Exists in Graph Leetcode Solution** Problem Statement Find if Path Exists in Graph Leetcode Solution – There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair ...

**Question 480. 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 481. 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 482. 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 483. 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 484. 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 485. 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 486. 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 487. 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 488. 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 489. Web Crawler LeetCode Solution** Problem Statement Web Crawler LeetCode Solution – Given a URL startUrl and an interface HtmlParser, implement a web crawler to crawl all links that are under the same hostname as startUrl. Return all URLs obtained by your web crawler in any order. Your crawler should: Start from the page: startUrl Call HtmlParser.getUrls(url) to get all URLs from a webpage of ...

**Question 490. 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 491. Cells with Odd Values in a Matrix LeetCode Solution** Problem Statement Cells with Odd Values in a Matrix LeetCode Solution – There is an m x n matrix that is initialized to all 0‘s. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix. For each location indices[i], we need to ...

**Question 492. 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 493. Possible Bipartition LeetCode Solution** Problem Statement Possible Bipartition LeetCode Solution – We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does ...

**Question 494. Employee Importance LeetCode Solution** Problem Statement Employee Importance LeetCode Solution – You have a data structure of employee information, including the employee’s unique ID, importance value, and direct subordinates’ IDs. You are given an array of employees employees where: employees[i].id is the ID of the ith employee. employees[i].importance is the important value of the ith employee. employees[i].subordinates is a list of the ...

**Question 495. 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 496. Kill Process LeetCode Solution** Problem Statement Kill Process LeetCode Solution – You have n processes forming a rooted tree structure. You are given two integer arrays pid and ppid, where pid[i] is the ID of the ith process and ppid[i] is the ID of the ith process’s parent process. Each process has only one parent process but may have multiple children processes. Only one process has ppid[i] = 0, ...

**Question 497. 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 498. 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 499. Design Hit Counter LeetCode Solution** Problem Statement Design Hit Counter LeetCode Solution – Design a hit counter which counts the number of hits received in the past 5 minutes (i.e., the past 300 seconds). Your system should accept a timestamp parameter (in seconds granularity), and you may assume that calls are being made to the system in chronological order (i.e., timestamp is monotonically increasing). ...

**Question 500. 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 501. 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 502. Consecutive Characters LeetCode Solution** Problem Statement Consecutive Characters LeetCode Solution – The power of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string s, return the power of s. Input: s = "leetcode" Output: 2 Explanation: The substring "ee" is of length 2 with the character 'e' only. Explanation ...

**Question 503. Champagne Tower LeetCode Solution** Problem Statement Champagne Tower LeetCode Solution – We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any ...

**Question 504. 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 505. 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 506. Image Overlap LeetCode Solution** Problem Statement Image Overlap LeetCode Solution – You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then ...

**Question 507. 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 508. 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 509. Find Two Non-overlapping Sub-arrays Each With Target Sum LeetCode Solution** Problem Statement The Find Two Non-overlapping Sub-arrays Each With Target Sum LeetCode Solution – “Find Two Non-overlapping Sub-arrays Each With Target Sum” states that you are given an integer array nums and an integer target, the task here is to find two non-overlapping subarrays from array nums such that the ...

**Question 510. Bold Words in String LeetCode Solution** Problem Statement Bold Words in String LeetCode Solution – Given an array of keywords words and a string s, make all appearances of all keywords words[i] in s bold. Any letters between <b> and </b> tags become bold. Return s after adding the bold tags. The returned string should use the least number of tags possible, and the tags should form a ...

**Question 511. 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 512. 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 513. Reverse Only Letters LeetCode Solution** Problem Statement Reverse Only Letters LeetCode Solution – Given a string s, reverse the string according to the following rules: All the characters that are not English letters remain in the same position. All the English letters (lowercase or uppercase) should be reversed. Return s after reversing it. Input: s = "ab-cd" ...

**Question 514. 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 515. Encoded String With Shortest Length LeetCode Solution** Problem Statement Encoded String With Shortest Length LeetCode Solution – Given a string s, encode the string such that its encoded length is the shortest. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. k should be a positive integer. If an encoding process does not make the ...

**Question 516. 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 517. Largest Submatrix With Rearrangements LeetCode Solution** Problem Statement Largest Submatrix With Rearrangements LeetCode Solution – You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] Output: 4 ...

**Question 518. 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 519. 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 520. 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 521. 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 522. Remove All Occurrences of a Substring LeetCode Solution** Problem Statement The Remove All Occurrences of a Substring LeetCode Solution –“Remove All Occurrences of a Substring” states that remove ALL the occurrences of the substring part from the given input string s. Note: Substring is a contiguous sequence of characters in an input string. Example Explanation Let’s ...

**Question 523. 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 524. 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 525. 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 526. Find All Possible Recipes from Given Supplies LeetCode Solution** Problem Statement In this problem Find All Possible Recipes from Given Supplies LeetCode Solution, we are required to find the recipes that can be made using the supplies given as a vector of strings. We are also given the recipes we need to make and their corresponding ingredients required. Examples ...

**Question 527. 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 528. 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 529. 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 530. 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 531. Guess Number Higher or Lower LeetCode Solution** Problem Statement Guess Number Higher or Lower LeetCode Solution – We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I ...

**Question 532. Minimize Maximum Pair Sum in Array LeetCode Solution** Problem Statement Minimize Maximum Pair Sum in Array LeetCode Solution says the pair sum of a pair (a,b) is equal to a+b. The maximum pair sum is the largest pair sum in a list of pairs. For example, if we have pairs (2,6), (1,3), and (5,4), the maximum pair sum would be max(2+6, ...

**Question 533. 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 534. 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 535. 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 536. 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 537. 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 538. Kth Smallest Number in Multiplication Table Leetcode Solution** Problem Statement The Kth Smallest Number in Multiplication Table Solution – states that you are given the multiplication table matrix of size m x n, where matrix[i][j] = i*j (1 indexed). For the given three integers m,n and k, we need to find the kth smallest element in the m ...

**Question 539. Last Stone Weight II LeetCode Solution** Problem Statement The problem Last Stone Weight II says you are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y ...

**Question 540. 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 541. 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 542. 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 543. 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 544. 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 545. 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 546. 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 547. 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 548. 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 549. 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 550. 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 551. 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 552. 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 553. 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 554. Excel Sheet Column Title Leetcode Solution** Problem Statement In this problem a positive integer is given which represents a column number of an Excel sheet, we have to return its corresponding column title as appear in an Excel sheet. Example #1 28 "AB" #2 701 "ZY" Approach This problem is the reverse of the problem in ...

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

**Question 556. 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 557. 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 558. Valid Boomerang Leetcode Solution** Problem Statement In this problem, we are given a set of three points in an X-Y 2-D plane. We need to return whether they form a boomerang or not, that is whether they are any three distinct points and do not form a straight line. Example Points = {{1 , ...

**Question 559. 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 560. Shortest Completing Word Leetcode Solution** The problem Shortest Completing Word Leetcode Solution states that you are given a license plate and an array of os strings. You need to find the shortest completing word. A competing word is defined as a word that has all the alphabets in the license plate (case insensitive). The frequency ...

**Question 561. Subtract the Product and Sum of Digits of an Integer Leetcode Solution** Problem Statement In this problem, we need to find the difference between the product of digits and the sum of digits of a given positive integer. Example 1234 14 Explanation: Product = 4 * 3 * 2 * 1 = 24 and Sum = 4 + 3 + 2 + ...

**Question 562. Relative Ranks Leetcode Solution** The problem Relative Ranks Leetcode Solution asks us to return a vector or an array of strings representing the relative ranks. We are provided with an array that represents the score obtained by athletes. Then we use the given score array to assign the ranks. There is a small change ...

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

**Question 566. 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 567. Find the Difference Leetcode Solution** Problem statement In the problem “Find the Difference” we are given two strings s and t. String t is produced by randomly stuffing the characters of string s and adding one character at a random position. our task is to find out the character which was added in string t. ...

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

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

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

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

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

**Question 576. Find the Smallest Divisor given a Threshold Leetcode Solution** This post is on Find the Smallest Divisor given a Threshold Leetcode Solution Problem statement In the problem ” Find the Smallest Divisor Given a Threshold” we are given a nums array and a threshold value. A variable “result” is defined as the sum of all answers when elements in ...

**Question 577. 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 578. Maximum number of segments of lengths a, b and c** The problem “Maximum number of segments of lengths a, b and c” states that you are given a positive integer N, and you need to find the maximum number of segments of lengths a,b, and c that can be formed using N. Example N = 7 a = 5, b ...

**Question 579. 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 580. Count Primes in Ranges** Problem Statement The problem “Count Primes in Ranges” states that you are given a range [left, right], where 0<=left<=right<=10000. The problem statement asks to find out the total number of prime numbers within the range. Assuming that there will be a large number of queries. Example left: 4 right:10 2 ...

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

**Question 582. Largest divisible pairs subset** Problem Statement The problem “Largest divisible pairs subset” states that you are given an array of n distinct elements. Find the length of largest such that each pair of the subset has the larger element divisible by smaller elements. Example array = {1, 2, 4, 5, 8, 9, 16} 5 ...

**Question 583. Friends Pairing Problem** Problem Statement The “Friends Pairing Problem” states that there are N friends. And each them can remain single or be paired up with each other. But once a pair is made, those two friends can not take part in pairing. So, you need to find the total number of ways ...

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

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

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

**Question 587. 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 588. The Painter’s Partition Problem** Problem Statement The Painter’s Partition problem states that we have some fences and we have some painters. We want to minimize the time of painting all the fences by painters. There is a bound on the order of painting the fences by painters. Consider we have n painters, then painter ...

**Question 589. Super Ugly Number** Write a program to find the nth super ugly number. Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. Note: 1 is considered to be the first super ugly number. Approach 1: Brute force Main idea We will iterate ...

**Question 590. Huffman Coding** We have a message that we want to deliver. We want the message to be of least size possible so that the costs incurred in sending the message is low. Here we use the Huffman Coding concept to reduce the size of the message. Let’s assume that we have the ...

**Question 591. 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 592. Reverse Bits** Reverse bits of a given 32 bits unsigned integer. Example Input 43261596 (00000010100101000001111010011100) Output 964176192 (00111001011110000010100101000000) A 32-bit unsigned integer refers to a nonnegative number which can be represented with a string of 32 characters where each character can be either ‘0’ or ‘1’. Algorithm for i in range 0 ...

**Question 593. 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 594. 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 595. Split Array Into Consecutive Subsequences** Given a sorted array(in ascending order), check if the array can be split into 1 or more subsequences of length greater than equals to 3 such that every subsequence contains consecutive numbers. Examples Input: arr[] = {1,2,3,3,4,5} Output: true Explanation: The array can be split into 2 subsequences as, sub1[] ...

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

**Question 597. Minimum Cost to Hire K Workers** In minimum cost to hire K workers problem, we have given N workers from which we want to hire exactly k workers to form a paid group. The i-th worker has a quality[i] and a minimum wage expectation wage[i]. Pay will be given to them according to the following rules: ...

**Question 598. 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 599. 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 600. House Robber** The House Robber Problem states that, in a neighborhood in a city, there is a single row of n houses. A thief is planning to carry a heist in this neighborhood. He knows how much gold is concealed in each of the houses. However, in order to avoid triggering an ...

**Question 601. 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 602. 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 603. 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 604. Stone Game II Leetcode** What is Stone Game II Problem? Stone Game II LeetCode is a very famous problem on leetcode which is solved using the DP approach. The statement of the problem is described as two players A and B are playing a stone game. There are N number of piles each pile ...

**Question 605. 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 606. Stone Game LeetCode** What is Stone Game problem? Stone Game LeetCode – Two players A and B are playing a stone game. There are even numbers of piles each pile containing some stones and the total stones in all the piles is odd. A and B are supposed to pick a pile either ...

**Question 607. 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 608. 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 609. 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 610. 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 611. Sieve of Eratosthenes** Sieve of Eratosthenes is an algorithm in which we find out the prime numbers less than N. Here N is an integer value. This is an efficient method to find out the prime numbers to a limit. By using this we can find out the prime numbers till 10000000. Here ...

**Question 612. New 21 Game** New 21 Game is a problem that is based on the card game “21”. The problem statement of this problem is simple. We are initially having 0 points. If the value of our current points is less than K points then we draw numbers. During each draw we gain an ...

**Question 613. 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 614. Fibonacci numbers** Fibonacci numbers are the numbers that form the series called Fibonacci series and are represented as Fn. The first two Fibonacci numbers are 0 and 1 respectively i.e. F0=0 and F1=1. Starting from the third Fibonacci number each Fibonacci number is the sum of its previous two numbers in the ...

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