**Uber Technologies, Inc. **(**Uber**) is American mobility as a service provider, allowing users to book a car and a driver to transport them in a way similar to a taxi. It is based in San Francisco with operations in approximately 72 countries and 10,500 cities in 2021. Its services include ride-hailing, food delivery (Uber Eats and Postmates), package delivery, couriers, freight transportation, electric bicycle, and motorized scooter rental via a partnership with Lime, and Thames Clipper river bus transport in partnership with local operators. Uber does not own any vehicles but receives a commission from each booking. Fares, which vary using a dynamic pricing model based on local supply and demand at the time of the booking, are quoted to the customer in advance.

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

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

Categories of Questions

## Uber Array Questions

**Question 1. Minimum Increment to Make Array Unique Leetcode Solution** Problem Statement: Minimum Increment to Make Array Unique Leetcode Solution – You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1. Return the minimum number of moves to make every value in nums unique. ...

**Question 2. 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 3. 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 4. 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 5. 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 6. 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 7. 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 8. 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 9. 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 10. 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 11. 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 12. 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 13. 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 14. 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 15. Moving Average from Data Stream Leetcode Solution** Problem Statement The Moving Average from Data Stream LeetCode Solution – “Moving Average from Data Stream” states that given a stream of integers and a window size k. We need to calculate the moving average of all the integers in the sliding window. If the number of elements in the ...

**Question 16. Check Array Formation Through Concatenation Leetcode Solution** The problem Check Array Formation Through Concatenation Leetcode Solution provided us with an array of arrays. Along with that we are also given a sequence. We are then told to find if we can somehow construct the given sequence using array of arrays. We can arrange the arrays in any ...

**Question 17. 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 18. 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 19. 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 20. Find the Distance Value Between Two Arrays Leetcode Solution** The problem Find the Distance Value Between Two Arrays Leetcode Solution provides us two arrays arr1 and arr2. Along with the two arrays, we are provided with an integer n. Then the problem asks us to find the relative distance between the given two arrays. The relative distance is defined ...

**Question 21. Find Common Characters Leetcode Solution** Problem Statement In this problem, we are given a list of string. We have to find out the characters that are common in all the strings. If a character is present in all strings in multiple times, then we have to output the character multiple times. Suppose, we have array ...

**Question 22. Minimum Absolute Difference Leetcode Solution** The problem Minimum Absolute Difference Leetcode Solution provides us an unsorted array or vector containing some integers. We are required to find out all the pairs that have a difference equal to that of minimum absolute difference. The minimum absolute difference is the minimum value of absolute difference that can ...

**Question 23. 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 24. 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 25. 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 26. 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 27. Running Sum of 1d Array Leetcode Solution** Problem Statement In running sum of 1d array problem we have been given an array nums for which we have to return an array where for each index i in the result array arr[i] = sum( nums[0] … nums[i] ). Example nums = [1,2,3,4] [1,3,6,10] Explanation: Running sum is : ...

**Question 28. 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 29. 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 30. 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 31. 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 32. Best Time to Buy and Sell Stock II Leetcode Solution** Problem statement In the problem “Best Time to Buy and Sell Stock II,” we are given an array where each element in the array contains the price of the given stock on that day. The definition of the transaction is buying one share of stock and selling that one share ...

**Question 33. 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 34. 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 35. 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 36. 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 37. 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 38. 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 39. 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 40. 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 41. Stock Buy Sell to Maximize Profit** Problem Statement In the “Stock Buy Sell to Maximize Profit” problem we have given an array that contains stock price on each day, find the maximum profit that you can make by buying and selling in those days. Here, we can buy and sell multiple times but only after selling ...

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

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

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

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

**Question 51. 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 52. 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 53. 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 54. 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 55. 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 56. 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 57. Find a Fixed Point in a Given Array** Problem Statement Given an array of n distinct elements, find a fixed point in a given array, where a fixed point means the element value is the same as the index. Example Input 5 arr[] = {0,4,8,2,9} Output 0 is a fixed point in this array because value and index ...

**Question 58. 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 59. 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 60. 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 61. 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 62. Find Minimum Distance Between Two Numbers in an Array** Problem Statement In the given unsorted array, which may also contain duplicates, find the minimum distance between two different numbers in an array. Distance between 2 numbers in an array: the absolute difference between the indices +1. Example Input 12 3 5 4 2 6 5 6 6 5 4 ...

**Question 63. 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 64. 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 ...

## Uber String Questions

**Question 65. 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 66. 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 67. 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 68. Minimum Remove to Make Valid Parentheses LeetCode Solution** Problem Statement The Minimum Remove to Make Valid Parentheses LeetCode Solution – You are given a string s of ‘(‘, ‘)’ and lowercase English characters. Your task is to remove the minimum number of parentheses ( ‘(‘ or ‘)’, in any positions ) so that the resulting parentheses string is ...

**Question 69. 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 70. 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 71. 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 72. 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 73. 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 74. 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 75. 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 76. 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 77. 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 78. 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 79. 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 80. 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 81. 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 82. 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 83. 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 84. 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 85. 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 ...

## Uber Tree Questions

**Question 86. 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 87. Vertical Order Traversal of Binary Tree LeetCode Solution** Problem Statement Vertical Order Traversal of Binary Tree LeetCode Solution says – Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. ...

**Question 88. 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 89. 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 90. 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 91. 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 92. 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 93. 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 94. 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 95. 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 96. 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 97. 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 98. 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 99. Recover Binary Search Tree** Consider a binary search tree, two nodes of the tree have been swapped, design an algorithm to recover the binary search Tree. Example Consider the binary search tree given below whose two nodes have been swapped as input. Incorrect nodes on the BST are detected(highlighted) and then swapped to obtain ...

## Uber Graph Questions

**Question 100. 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 101. 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 102. 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 103. 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 104. 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 ...

## Uber Stack Questions

**Question 105. 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 106. 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 107. 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 108. 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 109. Minimum Remove to Make Valid Parentheses LeetCode Solution** Problem Statement The Minimum Remove to Make Valid Parentheses LeetCode Solution – You are given a string s of ‘(‘, ‘)’ and lowercase English characters. Your task is to remove the minimum number of parentheses ( ‘(‘ or ‘)’, in any positions ) so that the resulting parentheses string is ...

**Question 110. 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 111. 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 112. Max stack** Problem Statement The problem “Max stack” states to design a special stack which can perform these operations : push(x): push one element into the stack. top(): returns the element that is at the top of the stack. pop(): remove the element from the stack which is at the top. peekmax(): ...

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

## Uber Queue Questions

**Question 114. Moving Average from Data Stream Leetcode Solution** Problem Statement The Moving Average from Data Stream LeetCode Solution – “Moving Average from Data Stream” states that given a stream of integers and a window size k. We need to calculate the moving average of all the integers in the sliding window. If the number of elements in the ...

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

## Uber Matrix Questions

**Question 116. 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 117. 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 118. 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 119. 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 120. 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. ...

## Uber Other Questions

**Question 121. 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 122. 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 123. Implement Rand10() Using Rand7() Leetcode Solution** Problem Statement: Implement Rand10() Using Rand7() Leetcode Solution – Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that produces a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn’t call any other ...

**Question 124. Contains Duplicate LeetCode Solution** Problem Statement: Contains Duplicate LeetCode Solution says that- Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: ...

**Question 125. 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 126. Reverse Nodes in k-Group LeetCode Solution** Problem Statement: Reverse Nodes in k-Group LeetCode Solution – Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is ...

**Question 127. 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 128. 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 129. 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 130. 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 131. 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 132. 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 133. 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 134. Next Greater Element I Leetcode Solution** Problem Statement Next Greater Element I Leetcode Solution – The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine ...

**Question 135. 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 136. 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 137. Valid Triangle Number LeetCode Solution** Problem Statement Valid Triangle Number LeetCode Solution – Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. Input: nums = [2,2,3,4] Output: 3 Explanation: Valid combinations are: 2,3,4 (using the first 2) ...

**Question 138. 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 139. 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 140. 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 141. 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 142. 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 143. Palindrome Number LeetCode Solution** Problem Statement Palindrome Number LeetCode Solution says that – Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. For example, 121 is a palindrome while 123 is not. Example 1: Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right ...

**Question 144. Valid Triangle Number LeetCode Solution** Problem Statement: Valid Triangle Number LeetCode Solution says – Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. Example 1: Input: nums = [2,2,3,4] Output: 3 Explanation: Valid combinations are: 2,3,4 (using ...

**Question 145. 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 146. 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 147. 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 148. 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 149. 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 150. 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 151. 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 152. Nearest Exit from Entrance in Maze LeetCode Solution** Problem Statement Nearest Exit from Entrance in Maze LeetCode Solution – We are given an m x n matrix “maze” (0-indexed) with empty cells represented as ‘.’ and walls as ‘+’. You are also given the entrance of the maze, where entrance = [entrance_row, entrance_col] denotes the row and column ...

**Question 153. 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 154. 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 155. 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 156. 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 157. 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 158. 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 159. 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 160. Largest Plus Sign Leetcode Solution** Problem Statement : Largest Plus Sign Leetcode Solution – You are given an integer n. You have an n x n binary grid with all values initially 1‘s except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0. Return the order of the largest axis-aligned plus ...

**Question 161. 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 162. 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 163. 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 164. 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 165. Zigzag Conversion LeetCode Solution** Problem Statement Zigzag Conversion LeetCode Solution – The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I ...

**Question 166. 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 167. 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 168. 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 169. 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 170. 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 171. 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 172. 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 173. 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 174. 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 175. 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 176. 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 177. 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 178. 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 179. 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 180. 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 181. 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 182. 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 183. 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 184. 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 185. 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 186. 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 187. 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 188. Remove Max Number of Edges to Keep Graph Fully Traversable Leetcode Solution** Problem Statement Remove Max Number of Edges to Keep Graph Fully Traversable Leetcode Solution- Alice and Bob have an undirected graph of n nodes and 3 types of edges: Type 1: Can be traversed by Alice only. Type 2: Can be traversed by Bob only. Type 3: Can be traversed by both ...

**Question 189. 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 190. 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 191. 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 192. 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 193. 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 194. Construct K Palindrome Strings LeetCode Solution** Problem Statement Construct K Palindrome Strings LeetCode Solution – Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise. Input: s = "annabelle", k = 2 Output: true Explanation: You can construct two palindromes using all characters in s. Some possible constructions "anna" ...

**Question 195. 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 196. 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 197. 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 198. 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 199. 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 200. Word Pattern LeetCode Solution** Problem Statement Word Pattern LeetCode Solution – We are given 2 strings – “s” and “pattern”, we need to find if the pattern follows s. Follows here means full match. More formally, we can for every pattern[i] there should only be one s[i] and vice versa i.e. there is a ...

**Question 201. 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 202. 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 203. 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 204. 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 205. Move Zeroes LeetCode Solution** Problem Statement The problem, Move Zeroes LeetCode Solution states that you are given an array containing zero and non-zero elements and you need to move all the zeroes to the end of the array, maintaining the relative order of non-zero elements in the array. You also need to implement an in-place ...

**Question 206. 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 207. 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 208. 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 209. Check If Array Pairs Are Divisible by k LeetCode Solution** Problem Statement Check If Array Pairs Are Divisible by k LeetCode Solution – Given an array of integers of even length n and an integer k. We want to divide the array into exactly n/2 pairs such that the sum of each pair is divisible by k. Return true If ...

**Question 210. 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 211. 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 212. 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 213. 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 214. 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 215. 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 216. 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 217. 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 218. 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 219. 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 220. 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 221. 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 222. Minimum Score Triangulation of Polygon Leetcode Solution** Problem statement In the problem ” Minimum Score Triangulation of Polygon” we are given a value array where each element in the array represents the value of a N-sided polygon when labeled in a clockwise direction. Our task is to triangulate the polygon into N-2 triangles. The score to triangulate ...

**Question 223. 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 224. Count ways to reach the nth stair using step 1, 2 or 3** The problem “Count ways to reach the nth stair using step 1, 2, or 3” states that you are standing on the ground. Now you need to reach the end of the staircase. So how many ways are there to reach the end if you can jump only 1, 2, ...

**Question 225. Maximum path sum in a triangle** Problem Statement The problem “Maximum path sum in a triangle” states that you are given some integers. These integers are arranged in the form of a triangle. You are starting from the top of the triangle and need to reach the bottom row. For doing this, you move to the ...

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

**Question 227. 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 228. 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 229. 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 230. 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 231. 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 232. 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 233. Maximum Length of Chain Pairs** Problem Statement In the maximum length of chain pairs problem we have given n pairs of numbers, find the longest chain in which (c, d) can follow (a, b) if b < c. In the given pairs the first element is always smaller than the second. Example Input [{12, 14}, ...