Find K Closest Elements LeetCode Solution

Difficulty Level Medium
Frequently asked in Amazon Apple Bloomberg ByteDance Facebook Goldman Sachs Google LinkedIn Microsoft Oracle PayPal Salesforce Uber
tiktokViews 34

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 - x| and a < b

 

Example 1:

Input:

Find K Closest Elements LeetCode SolutionPin
Find K Closest Elements LeetCode Solution
 arr = [1,2,3,4,5], k = 4, x = 3

Output:

 [1,2,3,4]

Example 2:

Input:

 arr = [1,2,3,4,5], k = 4, x = -1

Output:

 [1,2,3,4]

 

Constraints:

  • 1 <= k <= arr.length
  • 1 <= arr.length <= 104
  • arr is sorted in ascending order.
  • -104 <= arr[i], x <= 104

Approach

Idea:

  1. in this problem, we have to find the k nearest elements to an element x.
  2. first, we sort the array.
  3. then we find the lower bound of ele x in the array.
  4. lower bound returns an iterator pointing to the first element in the range [first, last) which has a value not less than val.
  5. we can say that arr[idx]>=x and also arr[idx-1]<x where idx is index of lower bound.
  6. now we apply 2 pointer approach to fit k elements inside our window
  7. we take two pointers where i=idx-1 and j=idx (here idx is an index of lower bound)
  8. now if i is close to x then we take ith ele and do i–
  9. otherwise, we take jth element and do j++

Code:

Find K Closest Elements C++ Solution:

vector<int> findClosestElements(vector<int>& arr, int k, int x) {
       
       sort(arr.begin(),arr.end());
       
       vector<int> ans;
       
       auto lowerBound=lower_bound(arr.begin(),arr.end(),x);
       
       
       int idx=lowerBound-arr.begin();  
       int i=idx-1,j=idx;
       
      while(i>=0 && j<arr.size())
      {
          int diff1=x-arr[i],diff2=arr[j]-x;
          
          if(diff1<=diff2)
          {
              ans.push_back(arr[i]);
              i--;
          }
          else
          {
              ans.push_back(arr[j]);
              j++;
          }
          
          if(ans.size()==k){
              
              break;}
          
      }
       
      if(i>=0)
      {
          while(ans.size()!=k)
          {
              ans.push_back(arr[i]);
              i--;
          }
      }
       
       if(j<arr.size())
       {
            while(ans.size()!=k)
          {
              ans.push_back(arr[j]);
              j++;
          }
       }
       
       sort(ans.begin(),ans.end());
       
       return ans;
       
       
       
       
   }

Find K Closest Elements Java Solution:

class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        int n = arr.length;
       
        int l = 0, r = n - 1, lowerBoundIdx = n;
        while(l <= r) {
            int m = l + (r - l) / 2;
            if(arr[m] <x) {
              
                l = m + 1;
            }
            else {
                lowerBoundIdx = m;
                r = m - 1;
            }
        }
        
        int i=lowerBoundIdx-1,j=lowerBoundIdx;
        List<Integer> ans = new ArrayList<>();
         while(i>=0 && j<n)
       {
           int diff1=x-arr[i],diff2=arr[j]-x;
           
           if(diff1<=diff2)
           {
               ans.add(arr[i]);
               i--;
           }
           else
           {
               ans.add(arr[j]);
               j++;
           }
           
           if(ans.size()==k){
               
               break;}
           
       }
        
       if(i>=0)
       {
           while(ans.size()!=k)
           {
               ans.add(arr[i]);
               i--;
           }
       }
        
        if(j<n)
        {
             while(ans.size()!=k)
           {
               ans.add(arr[j]);
               j++;
           }
        }
        Collections.sort(ans);
        return ans;
    }
}

Complexity Analysis:

Time Complexity:

The Time Complexity of the above solution is O(logn).

Space Complexity:

The Space Complexity of the above solution is O(1) since we are using constant extra space.

Top Interview Questions

S.No Interview Question Number of times has been asked
1Delete a node in doubly linked list2819
2Java program to find the number of Nodes in a Binary Tree2500
3Reverse a string without affecting special characters2460
4Delete a node of a linked list at given position1976
5Palindrome using Recursion1779
6Insert nodes in a linked list in a sorted way (Ascending Order)1662
7Find elements pair from array whose sum equal to number1644
8Sort Elements by Frequency of Occurrences1631
9Write a program to print all permutations of a given string1605
10Find Minimum Distance Between Two Numbers in an Array1472
11Create a Doubly Linked List1444
12Quick Sort1419
13Reverse an Array1414
14Smallest window in a string containing all characters of another string1395
15Find a Triplet That Sum to a Given Value1356
16Recursively remove all adjacent duplicates1353
17First Repeating Element1337
18Arrange Even and Odd number such that Odd comes after Even1320
19Sum of numbers in String1315
20Smallest Positive Number Missing in an Unsorted Array1283
21Check if the Elements of an Array are Consecutive1252
22Detect a loop in the Linked List1237
23Largest Sum Contiguous Subarray1229
24Quick Sort on SIngly Linked List1214
25Subarray with Given Sum1212
26Print all Possible Combinations of R Elements in a given Array of size N1204
27Recursive function to do substring search1196
28Find the Maximum Repeating Number in Array1155
29Binary Tree Level order traversal in Java1123
30Find the First and Second Smallest Elements1120
31Check if two linked lists are identical1102
32Maximum Subarray Sum using Divide and Conquer1098
33Remove characters from first string which are in second1070
34Find Leaders in an Array1060
35Swap nodes in the linked list1035
36Find the Number Occurring Odd Number of Times in an Array1001
37Arrange given Numbers to Form the Biggest Number II993
38Find the second most frequent character990
39Given a string find its first non-repeating character969
40Find Triplet in Array With a Given Sum964
41Given a sorted array and a number x, find the pair in array whose sum is closest to x954
42Total number of occurrences of a given item in the linked list951
43A Program to check if strings are rotations of each other or not943
44Print all possible words from phone digits933
45Find the Missing Number926
46Rearrange Positive and Negative Numbers Alternatively in Array920
47Longest Palindromic Substring905
48Segregate even and odd nodes in a linked list883
49Print Longest common subsequence882
50Union and Intersection of Two Linked Lists870
51Transform one string to another using minimum number of given operations867
52Rearrange given Array in Maximum Minimum Form845
53Check rearranged string can form a palindrome844
54Count Possible Triangles819
55Iterative Implementation of Quick Sort816
56Multiplication of Two Matrices801
57Check if the linked list is palindrome795
58Count of Triplets With Sum Less than Given Value790
59Rotate a Linked List790
60Stock Buy Sell to Maximize Profit786
61Concatenation of two strings761
62Tug of War759
63Count Number of Substrings with K Distinct Character’s758
64Print all duplicates in the input string753
65Find Nearest Greater and Smaller Element745
66The Celebrity Problem736
67Find Pythagorean Triplets from Array736
68Reverse String Without Temporary Variable734
69Remove ‘b’ and ‘ac’ from a given string728
70Find all Common Elements in Given Three Sorted Arrays727
71Remove all duplicates in an unsorted linked list709
72Find the Row with Maximum Number of 1’s705
73Find the Peak Element from an Array699
74Find the subarray whose sum is equal to a given number X695
75Remove Minimum Characters so that Two Strings Become Anagrams689
76Find Smallest Missing Number in a Sorted Array687
77Insertion Sort686
78A Product Array Puzzle685
79Addition of Two Matrices682
80Implement Two Stacks in an Array676
81Generate all Binary Strings Without Consecutive 1’s672
82Maximum Sum of Non Consecutive Elements667
83Maximum Product Subarray II658
84Lexicographic rank of string652
85Check if Two given Matrices are Identical644
86Multiplication of Previous and Next643
87Subtraction of Two Matrices632
88Merge K Sorted Arrays and Print Sorted Output631
89Move All the Zeros to the End of the Given Array627
90Online Algorithm for Checking Palindrome in a Stream623
91Form Minimum Number from Given Sequence of D’s and I’s622
92Divide a string in N equal parts622
93Check whether two strings are anagram of each other614
94Maximum Circular Subarray Sum613
95Remove recurring digits in a given number609
96Sort a stack using a temporary stack608
97Sort a linked list that is sorted alternating ascending and descending607
98Find the Minimum Element in a Sorted and Rotated Array604
99Move last element of the Linked List at first place601
100Subarray and Subsequence599
101First Circular Tour to Visit all the Petrol Bunks598
102Largest Subarray with Equal Number of 0’s and 1’s597
103Compare two strings(linked lists)592
104Flattening a linked list590
105Maximum Element in an Array which is Increasing and then Decreasing589
106Palindrome Permutations of a String584
107Elements Appear more than N/K times in Array581
108Majority Element575
109Run length encoding574
110Minimum insertions to form a shortest palindrome573
111Print all permutations with repetition572
112Palindromes in a given range571
113Pangram Checking569
114Merge a linked list into another at alternate positions568
115Minimum Characters to be Added at Front to Make String Palindrome564
116Remove all duplicates in a sorted linked list563
117Rearrange a given linked list in-place562
118Minimum number of Merge Operations to make an Array Palindrome560
119Most repeating character in a string558
120Rotate string to get lexicographically minimum string557
121Repeated Subsequence of Length Two or More554
122Print all anagrams together in a sequence of words552
123Reorder an Array According to the Given Indexes550
124Pancake Sorting Problem541
125Merge Overlapping Intervals II539
126Two Sum Leetcode Solution538
127Clone a Linked List with next and random pointer536
128Size of The Subarray With Maximum Sum528
129Transpose of a Matrix524
130Remove Extra Spaces from a String520
131Removing Spaces from a String using stringstream520
132Check if a given string is a rotation of a palindrome519
133Smallest Palindrome after Replacement518
134Remove duplicates from a string518
135Partition Problem517
136Maximum Sum Increasing Subsequence514
137Longest Palindrome can be Formed by Removing or Rearranging Characters513
138Check whether Strings are K Distance Apart or Not502
139Generate all Binary Strings from Given Pattern502
140Delete Last Occurrence500
141Length of Longest valid Substring499
142Find Zeros to be Flipped so that Number of Consecutive 1’s is Maximized499
143Insert Node in the Sorted Linked List498
1443Sum Leetcode Solution497
145Check if Two given Strings are Isomorphic to each other494
146Maximum difference between two elements such as larger element comes after smaller487
147Given string is interleaving of two other strings or not482
148Program to Toggle all Characters in a String482
149Count Minimum Steps to Get the given Array480
150Number of Smaller Elements on Right Side477
151Merge sort better than quick sort for linked lists477
152Find Pair with Given Difference472
153Check if all Rows of a Matrix are Circular Rotations of Each Other471
154Check length of a String is Equal to the Number Appended at its Last469
155Longest Common Prefix using Divide and Conquer468
156Find nth node of the Linked list from the end466
157Find a Fixed Point in a Given Array463
158Sort 0s 1s and 2s in an Array458
159Print all interleavings of given two strings457
160Compare Two Version Numbers456
161Reverse words in a given string455
162Merge two sorted linked lists such that merged list is in reverse order453
163Find the Subarray of given length with Least Average452
164Reorder Array Using Given Indexes451
165Split linked list using alternate nodes450
166Median of Two Sorted Arrays LeetCode Solution449
167Print Reverse of a string (Recursion)448
168Find K Length Subarray of Maximum Average439
169Print string of odd length in ‘X’ format435
170Find Element Using Binary Search in Sorted Array433
171Swap Kth Node from beginning with Kth Node from End431
172Print all Palindromic Partitions of a String429
173Find Duplicates in an Array in Most Efficient Way428
174print all palindromic partitions421
175Maximum Length of Chain Pairs416
176Shortest Superstring Problem415
177Flatten a multilevel linked list415
178Check if String Follows Order of Characters by a Pattern or not412
179Sorting a K Sorted Array409
180Sort a String According to Another String404
181Longest Span with same Sum in two Binary Arrays II398
182Reverse a Linked List in groups395
183Find a Sorted Subsequence of size 3393
184Program to add two binary digits390
185Recursively print all the sentences that can be formed from list of word lists388
186Find the two Numbers with Odd Occurrences in an Unsorted Array387
187Longest Common Prefix Using Binary Search II385
188Reverse a Singly Linked List (Iterative/Non-Recursive)382
189Caesar Cipher378
190Kth Non-repeating Character377
191Rearrange a linked list in Zig-Zag377
192Check if String can Become Empty by Recursively Deleting given Substring377
193Pancake Sorting373
194Rotate Image by 90 degrees371
195Longest Common Prefix Word by Word Matching369
196Perfect Reversible String366
197Permutations of a Given String Using STL364
198Merging Two Sorted Arrays362
199Increasing Subsequence of Length three with Maximum Product361
200Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes361
201Find First non-repeating character in a string358
202Find the point where a monotonically increasing function becomes positive first time358
203Sort a linked list with 0s, 1s and 2s357
2041`s and 2`s complement of binary number357
205Four Elements that Sum to Given353
206List items containing all characters of a given word352
207Delete N nodes after M351
208Count Number of Occurrences in a Sorted Array350
209Longest Common Prefix using Character by Character Matching348
210Palindrome string (number)342
211Split a string341
212Minimum Characters to be Removed to Make a Binary String Alternate339
213Recursive Implementation of atoi()333
214Check if a Linked list of Strings form a Palindrome333
215Print All Distinct Elements of the Array331
216Sorting the array of strings330
217Convert a String that is Repetition of a Substring of Length K330
218Maximum occurring character in a string326
219Find the first Repeating Number in a Given Array326
220Even Substring Count325
221Reverse a singly linked list recursively325
222Valid Parentheses LeetCode Solution325
223Binary Tree to Doubly linked list323
224Can we reverse a linked list in less than O(n) time ?323
225Print Shortest Path to Print a String on Screen322
226Maximum Subarray Leetcode Solution319
227Convert string1 to string2 in one edit319
228Reverse a String using Stack318
229Nth Character in Concatenated Decimal String318
230Sort Elements by Frequency II317
231wildcard character matching316
232Lower Case To Upper Case314
233Count the number of words313
234Merge Two Sorted Arrays311
235Find the Lost Element From a Duplicated Array310
236Split Four Distinct Strings309
237Find middle of the Linked List307
238Longest Common Subsequence with Permutations306
239Count the Pairs at Same Distance as in English Alphabets301
240Matrix Chain Multiplication using Dynamic Programming297
241Next Greater Element in an Array294
242Palindrome Permutation290
243Find Nth Node285
244Roman to Integer Leetcode Solution284
245Find All Pairs With a Given Difference283
246Searching a node in a Binary Search Tree283
247Triplet from three linked lists with given sum280
248Delete a Tree280
249String(represents an integer) to value278
250Print all Possible Ways to Break a String in Bracket Form277
251Reverse a String276
252Reverse Bits275
253Binary Tree273
254Word Search Leetcode Solution273
255Delete a node under given conditions272
256How to Efficiently Implement k Stacks in a Single Array?272
257Change Gender of a given String271
258Sort an array of strings270
259Count Pairs With Given Sum269
260Meeting Rooms II LeetCode Solution268
261Number of sub-strings which recursively add up to 9268
262Longest Common Extension267
263First non Repeating Element267
264Remove middle points in a linked list of line segments265
265Repeated Substring Pattern263
266Toeplitz Matrix263
267Move all negative elements to one side of array262
268Remove spaces from a string262
269Longest Palindromic Substring LeetCode Solution262
270Shuffle a given Array258
271N queen problem257
272Min Stack256
273Number of Islands LeetCode Solution251
274Find, second, frequent, character251
275House Robber Leetcode Solution250
276Dijkstra Algorithm250
277Cuckoo sequence program250
278Clone a linked list with next and random pointer (Hashing)248
279Max stack248
280Most Frequent Element in an Array247
281Search Insert Position Leetcode Solution246
282Minimize the maximum difference between the heights245
283Sort linked which is sorted on absolute values244
284Expression Evaluation244
285Subset Leetcode242
286Plus One Leetcode Solution241
287KMP Algorithm241
288Valid Palindrome Leetcode Solution241
289Fibonacci numbers240
290Evaluation of Postfix Expression239
291Min Stack Leetcode Solution239
292Word Search239
293How to Delete a Linked List238
294Sudoku Solver238
295Reverse words in a string238
296Combination Sum Leetcode Solution235
297Number Of 1 bits234
298Merge Sorted Arrays Leetcode Solution233
299Subarray with 0 sum230
300Sqrt(x) Leetcode Solution230
301Set Matrix Zeroes229
302Backspace String Compare229
303Rabin Karp Algorithm228
304Reversing a Queue227
305Contains Duplicate II Leetcode Solution227
306Pair of Positive Negative Values in an Array227
307Tower Of Hanoi224
308Combination Sum224
309Integer to Roman Leetcode Solution223
310Product of array except self223
311Common elements in all rows of a given matrix222
312Delete middle element of a stack222
313Pascal Triangle Leetcode222
314String Compression221
315Minimum swaps required to bring all elements less than or equal to k together220
316Intersection of Two Arrays II Leetcode Solution220
317Count subarrays with equal number of 1’s and 0’s219
318Reverse individual words218
319Sliding Window Technique217
320Segregate even and odd numbers217
321Add Binary Leetcode Solution217
322Find Top K (or Most Frequent) Numbers in a Stream216
323Arithmetic Expression Evaluation216
324Construct Binary Tree from Given Inorder and Preorder Traversals216
325Pow(x, n) Leetcode Solution216
326Second Most Repeated Word in a Sequence216
327Single Number Leetcode Solution216
328Implementation of Deque using Doubly Linked List215
329Bellman Ford Algorithm215
330Palindrome Linked List Leetcode Solution214
331Count of index pairs with equal elements in an array213
332Next Permutation213
333Count Odd Numbers in an Interval Range Leetcode Solution213
334Design a stack that supports getMin() in O(1) time and O(1) extra space212
335Maximum Number of Balloons Leetcode Solution212
336Minimum Value to Get Positive Step by Step Sum Leetcode Solution211
337Contains Duplicate211
338Kruskal Algorithm211
339Page Replacement Algorithms in Operating Systems210
340Sort elements by frequency210
341Third Maximum Number Leetcode Solution210
342Postfix to Infix Conversion209
343Find sum of non-repeating elements (distinct) elements in an array209
344K-th Smallest Element in a Sorted Matrix208
345Find Lucky Integer in an Array Leetcode Solution207
346Permutations Leetcode Solution207
347Longest Common Prefix Leetcode Solution207
348Convex Hull Algorithm207
349Find the Town Judge Leetcode Solution207
350Group Words With Same Set of Characters206
351Sum of minimum and maximum elements of all subarrays of size k206
352Find Numbers with Even Number of Digits Leetcode Solution206
353Maximum Subarray206
354Majority Element Leetcode Solution206
355Longest Substring Without Repeating Characters LeetCode Solution205
356Minimum operation to make all elements equal in array204
357Sorting array using Stacks204
358Scramble String204
359Top K Frequent Words203
360Count Primes Leetcode Solutions203
361Smallest Subarray with k Distinct Numbers203
362First element occurring k times in an array203
363Spiral Matrix LeetCode Solution203
364Swap Nodes in Pairs Leetcode Solutions202
365Count subarrays having total distinct elements same as original array202
366Check if two arrays are equal or not201
367Evaluate Division201
368Minimum Path Sum200
369Merge Two Sorted Lists Leetcode Solutions200
370Best Time to Buy and Sell Stock  II Leetcode Solution200
371Prefix to Infix Conversion200
372Given two unsorted arrays find all pairs whose sum is x200
373Special Number200
374Power of Two Leetcode Solution200
375Reverse a Number Using Stack199
376Fizz Buzz Leetcode199
377Search in Rotated Sorted Array Leetcode Solution198
378Number of Good Pairs Leetcode Solution198
379Pascal’s Triangle II Leetcode Solution198
380Reversing the First K elements of a Queue198
381Find All Numbers Disappeared in an Array Leetcode Solution197
382Group Anagrams197
383Find duplicates in a given array when elements are not limited to a range197
384House Robber II Leetcode Solution197
385Missing Number Leetcode Solution197
386Matrix Diagonal Sum Leetcode Solution196
387Leetcode Permutations196
388Maximal Square196
389Minimum Steps to reach target by a Knight196
390Huffman Coding196
391Maximum possible difference of two subsets of an array196
392Minimum Absolute Difference Leetcode Solution196
393Unique Paths Leetcode Solution195
394Maximum Distance Between two Occurrences of Same Element in Array195
395Running Sum of 1d Array Leetcode Solution195
396Coin Change 2 Leetcode Solution194
397Check if Array Contains Contiguous Integers With Duplicates Allowed194
398Top K Frequent Elements194
399Sorting using trivial hash function193
400Max Consecutive Ones Leetcode Solution193
401Single Number193
402Find The Duplicate Number193
403How to Implement Stack Using Priority Queue or Heap?193
404Average Salary Excluding the Minimum and Maximum Salary Leetcode Solution192
405Range Sum Query 2D – Immutable Leetcode Solution192
406Remove Duplicates from Sorted Array Leetcode Solution192
407Sort Array by Increasing Frequency Leetcode Solution192
408How Many Numbers Are Smaller Than the Current Number Leetcode Solution192
409Subarray Sum Equals k191
410Sort Integers by The Number of 1 Bit Leetcode Solution191
411Smallest Element Repeated Exactly K Times191
412Expression Contains Redundant Bracket or Not191
413Decode String191
414Unique Paths191
415Subarray Sum Equals K LeetCode Solution191
416Happy Number Leetcode Solution191
417Fibonacci Number LeetCode Solution191
418Reverse Vowels of a String Leetcode Solution190
419Find the Closest Palindrome number190
420Monotonic Array LeetCode Solution190
421Find Median from data Stream190
422Zigzag Conversion190
423Find Number of Employees Under every Employee190
424Reverse Integer190
425Delete a Node from linked list without head pointer189
426Shuffle the Array Leetcode Solution189
427Difference between highest and least frequencies in an array189
428Find Winner on a Tic Tac Toe Game Leetcode Solution189
429Nth Catalan Number189
430Subset sum problem189
431Subtract the Product and Sum of Digits of an Integer Leetcode Solution189
432LRU Cache Implementation188
433Palindrome Substring Queries188
434Implement Stack and Queue using Deque188
435Trapping Rain Water Leetcode Solution188
436Length of the largest subarray with contiguous elements188
437Count Substrings with equal number of 0s, 1s and 2s188
438Cumulative Frequency of Count of Each Element in an Unsorted Array188
439Reverse Words in a String III LeetCode Solution187
440Subarrays with distinct elements187
441Check If N and Its Double Exist Leetcode Solution187
442Maximum Depth of Binary Tree Leetcode Solution187
443Print All Distinct Elements of a Given Integer Array187
444Find top three repeated in array187
445Convert String To Int187
446Letter Case Permutation187
447Capacity To Ship Packages Within D Days Leetcode Solution186
448Kth largest element in an Array Leetcode Solutions186
449Sort a stack using recursion186
450The K Weakest Rows in a Matrix Leetcode Solution186
451Find all pairs (a, b) in an array such that a % b = k186
452Find the Duplicate Element186
453Excel Sheet Column Number Leetcode Solution185
454Bipartite Graph185
455Integer to English words185
456Reverse a Stack Using Recursion185
457Minimum Moves to Equal Array Elements Leetcode Solution185
458Best Time to Buy and Sell Stock III Leetcode Solution185
459Sorting a Queue without Extra Space184
460Find the first repeating element in an array of integers184
461Find Minimum In Rotated Sorted Array184
462Iterative Tower of Hanoi184
463Merge Two Sorted Linked Lists184
464Prim’s Algorithm184
465Generate a String With Characters That Have Odd Counts Leetcode Solution184
466Concatenation of Array LeetCode Solution184
467Floyd Warshall Algorithm183
468Priority Queue Using Singly Linked List183
469Count pairs from two linked lists whose sum is equal to a given value183
470Find the Difference Leetcode Solution183
471Edit Distance182
472Next Greater Element I Leetcode Solution182
473Find First and Last Position of Element in Sorted Array Leetcode Solution182
474Longest Common Subsequence182
475Reverse a String182
476Sum of Subarray Ranges Leetcode Solution182
477Multiply Strings Leetcode Solution182
478Flood Fill LeetCode182
479Move Zeroes LeetCode Solution182
480Kth Largest Element in a Stream Leetcode Solution181
481Remove Minimum Number of Elements Such That no Common Element Exist in both Array181
482Text Justification LeetCode Solution181
483Find Common Characters Leetcode Solution181
484Count and Say181
485Merge Overlapping Intervals181
486Slowest Key Leetcode Solution181
487Find elements which are present in first array and not in second181
488Word Ladder LeetCode Solution181
489Balanced Binary Tree Leetcode Solution180
490Top View of Binary Tree180
491Print all subarrays with 0 sum180
492Number of Steps to Reduce a Number to Zero Leetcode Solution180
493Degree of an array180
494Fizz Buzz180
495Kids With the Greatest Number of Candies Leetcode Solution180
496MiniMax Algorithm180
497Target Sum180
498Longest Common Prefix using Trie180
499Reverse a linked list179
500Zigzag Conversion LeetCode Solution179
501Design Parking System Leetcode Solution179
502Jump Game Leetcode Solution179
503Convert array into Zig-Zag fashion178
504Intersection of Two Arrays178
505Find subarray with given sum (Handles Negative Numbers)178
506Pair with given product178
507Priority Queue in C++177
508Length of Last Word Leetcode Solution177
509Longest subarray not having more than K distinct elements177
510Count and Say Leetcode Solution177
511Last Stone Weight177
512Max Area of Island177
513Valid Parenthesis String177
514Check if a given array contains duplicate elements within k distance from each other177
515Shuffle String Leetcode Solution176
516Koko Eating Bananas Leetcode Solution176
517Peak Index in a Mountain Array176
518Find four elements that sum to a given value (Hashmap)176
519Shortest Palindrome176
520Postfix to Prefix Conversion176
521Find N Unique Integers Sum up to Zero Leetcode Solution176
522The Stock Span Problem176
523Find missing elements of a range175
524Mobile Numeric Keypad Problem175
525Longest Common Prefix using Sorting175
526Prefix to Postfix Conversion175
527Find distinct elements common to all rows of a matrix174
528N-th Tribonacci Number Leetcode Solution174
529Find Index of Closing Bracket for a Given Opening Bracket in an Expression174
530Relative Sort Array Leetcode Solution174
531Find any one of the multiple repeating elements in read only array174
532K-th Distinct Element in an Array174
533Substring With Concatenation Of All Words174
534Recursion174
535Contiguous Array Leetcode174
536Count number of triplets with product equal to given number174
537Iterative Inorder Traversal of a Binary Tree174
538Implement a stack using single queue174
539Smallest Subarray With all Occurrences of a Most Frequent Element174
540Valid Anagrams173
541Largest Perimeter Triangle Leetcode Solution173
542Valid Sudoku173
543Is Subsequence Leetcode Solution173
544Container with Most Water173
545Implementation of Deque using circular array173
546Implement Stack using Queues173
547Delete Node in a Linked List Leetcode Solution173
548Excel Sheet Column Title Leetcode Solution173
549Linked List Cycle II LeetCode Solution172
550Build Array From Permutation Leetcode Solution172
551First negative integer in every window of size k172
552Best Time to Buy and Sell Stock172
553Sum of Left Leaves Leetcode Solutions172
55401 Matrix LeetCode Solution172
555Next Greater Frequency Element172
556Maximum sum rectangle in a 2D matrix172
557Isomorphic Strings Leetcode Solution172
558Island Perimeter Leetcode Solution172
559Convert a normal BST to Balanced BST171
560Trapping Rain Water LeetCode Solution171
561Minimum Delete Operations to make all Elements of Array Same171
562Find Words That Can Be Formed by Characters Leetcode Solution171
563Distribute Candies to People Leetcode Solution171
564Minimum Operations to convert X to Y171
565Count the number of nodes at given level in a tree using BFS170
566Hamming Distance170
567Minimum Bracket Reversals170
568Rearrange a binary string as alternate x and y occurrences170
569Arrange given numbers to form the biggest number170
570Shuffle an Array170
571Jewels and Stones Leetcode Solution170
572Remove Linked List Elements Leetcode Solution170
573Count all subsequences having product less than K169
574The Knapsack Problem169
575Gold Mine Problem169
576Assign Cookies Leetcode Solution169
577Convert Sorted Array to Binary Search Tree Leetcode Solution169
578Insert Interval Leetcode Solution169
579Integer to Roman169
580Change the Array into Permutation of Numbers From 1 to N168
581Check for Balanced Parentheses in an Expression168
582Maximum path sum in a triangle168
583Shortest Path in a Grid with Obstacles Elimination LeetCode Solution168
5843Sum Closest LeetCode Solution168
585Summary Ranges Leetcode Solution168
586Group Multiple Occurrence of Array Elements Ordered by first Occurrence168
587Find the smallest positive integer value that cannot be represented as sum of any subset of a given array168
588Minimum Knight Moves LeetCode Solution168
589Rotate List Leetcode Solution167
590XOR Operation in an Array Leetcode Solution167
591Unique Binary Search Trees167
592Minimum number of distinct elements after removing m items167
593K Empty Slots LeetCode167
594Decode Ways167
595LRU Cache LeetCode Solution167
596Rotate Image LeetCode Solution166
597How to check if two given sets are disjoint?166
598Same Tree LeetCode Solution166
599Distance Between Bus Stops Leetcode Solution166
600Sieve of Eratosthenes166
601Combinations Leetcode Solution166
602Maximum Distance in Array166
603Frog Jump Leetcode Solution165
604Permutation in String Leetcode Solution165
605Find minimum difference between any two elements165
606Remove All Occurrences of a Substring LeetCode Solution165
607Maximum difference between first and last indexes of an element in array165
608Sort Characters By Frequency LeetCode Solution165
609Stone Game LeetCode165
610Painting Fence Algorithm164
611Word Wrap Problem164
612Word Pattern164
613Best Time to Buy and Sell Stock LeetCode Solution164
614Segregate 0s and 1s in an Array164
615Find Sum of all unique sub-array sum for a given array164
616Minimum number of subsets with distinct elements164
617License Key Formatting Leetcode Solution164
618Replace Elements with Greatest Element on Right Side Leetcode Solution164
619Printing brackets in Matrix Chain Multiplication Problem164
620Minimum insertions to form a palindrome with permutations allowed163
621Smallest Good Base163
622Sort Array By Parity LeetCode Solution163
623Find if an Expression has Duplicate Parenthesis or Not163
624Minimum Depth of Binary Tree Leetcode Solution163
625Defanging an IP Address Leetcode Solution162
626Applications of Breadth First Search and Depth First Search162
627Kth Missing Positive Number Leetcode Solution162
628Find the Duplicate Number LeetCode Solution162
629Maximum Number of Chocolates to be Distributed Equally Among k Students162
630Distance of nearest cell having 1 in a binary matrix162
631Coin Change Problem162
632Tracking current Maximum Element in a Stack161
633Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest161
634Valid Palindrome II Leetcode Solution161
635House Robber161
636Minimum Cost to Hire K Workers161
637Iterative Method to find Height of Binary Tree160
638Isomorphic Strings160
639Find Maximum Level sum in Binary Tree160
640Longest Increasing Subsequence160
641Delete consecutive same words in a sequence160
642Sum of All Odd Length Subarrays Leetcode Solution160
643Binary Tree Zigzag Level Order Traversal LeetCode Solution160
644Maximum Consecutive Numbers Present in an Array160
645Power of Four Leetcode Solution160
646Optimal Account Balancing LeetCode Solution160
647Non-overlapping sum of two sets160
648Count Good Nodes in Binary Tree Leetcode Solution160
649Minimum Number of Steps to Make Two Strings Anagram Leetcode Solutions160
650Longest Substring with At Most K Distinct Characters LeetCode Solution160
651Reverse a stack without using extra space in O(n)159
652Number of Provinces Leetcode Solution159
653Ugly Number Leetcode Solution159
654Merge Two Balanced Binary Search Trees159
655Moving Average from Data Stream Leetcode Solution159
656Best Time to Buy and Sell Stock with Cooldown Leetcode Solution159
657GCD Of Two Numbers159
658K Empty Slots159
659Check If It Is a Straight Line Leetcode Solution159
660Convert an array to reduced form158
661Maximum Number of Coins You Can Get Leetcode Solution158
662Largest Sum Contiguous Subarray158
663Number of Dice Rolls With Target Sum LeetCode Solution158
664Letter Combinations of a Phone Number158
665Check if a queue can be sorted into another queue using a stack158
666String to Integer (atoi) LeetCode Solution158
667Check If Two String Arrays are Equivalent Leetcode Solution158
668Queries for counts of array elements with values in given range158
669Strobogrammatic Number LeetCode Solution158
670Wiggle Sort158
671Reducing Dishes LeetCode Solution157
672Form minimum number from given sequence157
673Employee Free Time LeetCode Solution157
674Reverse Only Letters LeetCode Solution157
675Longest Substring with At Least K Repeating Characters LeetCode Solution157
676Sum of f(a[i], a[j]) over all pairs in an array of n integers157
677Reorganize String157
678Longest Increasing Path in a Matrix LeetCode Solution157
679Increasing Decreasing String Leetcode Solution157
680Subset Sum Leetcode157
681How to Create Mergable Stack?157
682Partition Labels LeetCode Solution157
683Find Largest d in Array such that a + b + c = d157
684Find the Smallest Divisor given a Threshold Leetcode Solution157
685Flipping an Image LeetCode Solution157
686Lucky Numbers in a Matrix Leetcode Solution157
687Print the Fibonacci numbers in reverse order157
688Inorder Successor of a node in Binary Tree156
689Path With Maximum Minimum Value LeetCode Solution156
690Valid Perfect Square Leetcode Solution156
691Find Leaves of Binary Tree LeetCode Solution156
692Find whether an array is subset of another array156
693Unique Paths II Leetcode Solution156
694Maximum Number of Occurrences of a Substring Leetcode Solution156
695Reversing a Queue using Recursion156
696Valid Palindrome156
697Find the Distance Value Between Two Arrays Leetcode Solution156
698Robot Room Cleaner Leetcode Solution155
699Construct BST from given Preorder Traversal155
700Partition Array Into Three Parts With Equal Sum Leetcode Solution155
701Permutation Sequence LeetCode Solution155
702BFS vs DFS for Binary Tree155
703To Lower Case Leetcode Solution155
704Dynamic Programming Basics155
705Majority Element II Leetcode Solution155
706Binary Tree zigzag level order Traversal155
707Delete Nth node from the end of the given linked list155
708Recover Binary Search Tree155
709Merge Two Binary Trees LeetCode Solution155
710Populating Next Right Pointers in Each Node155
711Reservoir Sampling155
712Maximum Product of Two Elements in an Array Leetcode Solution155
713Maximum Product of Three Numbers LeetCode Solution154
714Find the node with minimum value in a Binary Search Tree154
715Add and Search Word – Data structure design LeetCode154
716Hamming Distance Leetcode Solution154
717Find pairs with given sum such that elements of pair are in different rows154
718Rank Transform of an Array Leetcode Solution154
719Edit Distance LeetCode Solution154
720Sort Array by Increasing Frequency Leetcode Solution154
721Remove Invalid Parentheses Leetcode Solution154
722Factorial Trailing Zeroes Leetcode Solution153
723Keyboard Row Leetcode Solution153
724Restore IP Addresses Leetcode Solution153
725Decompress Run-Length Encoded List Leetcode Solution153
726Convert a Number to Hexadecimal Leetcode Solution153
727Numbers with prime frequencies greater than or equal to k153
728Deletion in a Binary Tree152
729Bulb Switcher LeetCode Solution152
730Stack Permutations (Check if an array is stack permutation of other)152
731Queue based approach for first non-repeating character in a stream152
732String Compression LeetCode Solution152
733Longest Span with same Sum in two Binary arrays152
734Minimum Height Trees151
735Binary Tree Maximum Path Sum LeetCode Solution151
736Linked List Cycle151
737Find the largest multiple of 3151
738Find unique character in a string151
739Race Car LeetCode Solution151
740Symmetric Tree Leetcode Solution151
741Search in a Binary Search Tree Leetcode Solution151
742Non-decreasing Array LeetCode Solution151
743Minimum Distance Between BST Nodes Leetcode Solution151
744Find All Duplicates in an Array LeetCode Solution151
745Largest subarray with equal number of 0s and 1s151
746Find Maximum Depth of Nested Parenthesis in a String151
747Sorted Linked List to Balanced BST150
748Maximum 69 Number Leetcode Solution150
749First Unique Character in a String LeetCode Solution150
750Remove Duplicates from Sorted List LeetCode Solution150
751Best Meeting Point LeetCode Solution150
752Remove Nth Node From End of List Leetcode Solution150
753Bubble sort using two Stacks150
754Check If Array Pairs Are Divisible by k LeetCode Solution150
755Minimum Cost For Tickets Leetcode Solution150
756Generate all possible sorted arrays from alternate elements of two given sorted arrays150
757Find Pair with Greatest Product in Array150
758Invert Binary Tree LeetCode Solution150
759Perform String Shifts Leetcode150
760Maximum Length of a Concatenated String with Unique Characters Leetcode Solution150
761Find if Path Exists in Graph Leetcode Solution150
762k-th missing element in increasing sequence which is not present in a given sequence150
763Word Pattern LeetCode Solution150
764Minimize Maximum Pair Sum in Array LeetCode Solution150
765Binomial Coefficient150
766Student Attendance Record I Leetcode Solution149
767Number of Islands II LeetCode Solution149
768Kth ancestor of a node in binary tree149
769Jump Game149
770Finding K closest element149
771Morris Traversal149
772Find Median from Data Stream LeetCode Solution149
773Search a 2D Matrix II Leetcode Solution149
774Count quadruples from four sorted arrays whose sum is equal to a given value x149
775Maximum Difference Between Increasing Elements LeetCode Solution149
776Growable array based stack149
777N-Queens LeetCode Solution149
778Merge K Sorted Linked Lists149
779Evaluate Reverse Polish Notation LeetCode Solution149
780Diagonal Traversal of Binary Tree149
781Elements to be added so that all elements of a range are present in array149
782Maximum Depth of N-ary Tree Leetcode Solution148
783Largest rectangular sub-matrix whose sum is 0148
784Number Complement Leetcode Solution148
785Minimum time required to rot all oranges148
786Split a String in Balanced Strings Leetcode Solution148
787Valid Number148
788Remove brackets from an algebraic string containing + and – operators148
789Program for Bridge and Torch problem148
790Minimum Time Visiting All Points Leetcode Solution148
791Snakes and Ladders LeetCode Solution148
792Transpose Graph147
793Largest Rectangle in Histogram LeetCode Solution147
794Minimum number of jumps to reach end147
795Nearest Exit from Entrance in Maze LeetCode Solution147
796Count items common to both the lists but with different prices147
797Remove Duplicates from Sorted List II147
798Sort an array according to the order defined by another array147
799Nested List Weight Sum II LeetCode Solution147
800Merge Sorted Array LeetCode Solution147
801Relative Ranks Leetcode Solution147
802Check for Palindrome after every character replacement Query147
803Special Array With X Elements Greater Than or Equal X Leetcode Solution147
804Number of NGEs to the Right147
805Get Maximum in Generated Array Leetcode Solution147
806Tiling Problem146
807Longest Subarray Having Count of 1s One More than Count of 0s146
808Friends Pairing Problem146
809Crawler Log Folder Leetcode Solution146
810Partition to K Equal Sum Subsets Leetcode Solution146
811Base 7 Leetcode Solution146
812Print a Binary Tree in Vertical Order146
813Sort Array By Parity II Leetcode Solution146
814Sort Colors146
815A Space Optimized DP solution for 0-1 Knapsack Problem146
816Final Prices With a Special Discount in a Shop Leetcode Solution146
817One Edit Distance LeetCode Solution146
818Convert BST to Min Heap146
819String comparison containing wildcards146
820Minimum Number of Taps to Open to Water a Garden LeetCode Solution146
821Circular Queue146
822Sorted Array to Balanced BST145
823Alien Dictionary LeetCode Solution145
824Minimum swaps to make sequences increasing145
825Reorder Data in Log Files LeetCode Solution145
826Path with maximum average value145
827Regular Expression Matching145
828Clone Graph LeetCode Solution145
829Subarray Product Less Than K LeetCode Solution145
830Subsequence of Size K With the Largest Even Sum LeetCode Solution145
831Check if Two Expressions With Brackets are Same145
832Interval Tree145
833Make Two Arrays Equal by Reversing Sub-arrays Leetcode Solution144
834Total Numbers With no Repeated Digits in a Range144
835Guess Number Higher or Lower LeetCode Solution144
836Priority Queue using doubly linked list144
837Maximum Profit in Job Scheduling Leetcode Solution144
838Minimum Jumps to Reach Home LeetCode Solution144
839Last Stone Weight II LeetCode Solution144
840Design a Stack With Increment Operation Leetcode Solution144
841Level order Traversal in Spiral Form144
842Iterative Preorder Traversal144
843Insert into a Binary Search Tree Leetcode Solution144
844Partition List Leetcode Solution144
845Minimum Swaps to Make Strings Equal Leetcode Solution144
846Maximum size subarray sum equals k144
847Course Schedule II – LeetCode144
848Check if a given array can represent Preorder Traversal of Binary Search Tree144
849Find the subarray with least average144
850Count Distinct Elements in Every Window of Size K143
851Can Place Flowers LeetCode Solution143
852Permutation Coefficient143
853Brightest Position on Street LeetCode Solution143
854Valid Parentheses Leetcode Solution143
855Find all triplets with zero sum143
856Find the Only Repetitive Element Between 1 to N-1143
857Top K Frequent Words LeetCode Solution143
858Union and Intersection of two Linked Lists143
859Minimum Sum Path in a Triangle143
860Subset with sum divisible by m143
861Brick Wall LeetCode Solution142
862Water Bottles Leetcode Solution142
863Three way partitioning of an array around a given range142
864Given an Array of Pairs Find all Symmetric Pairs in it142
865Check whether a given Binary Tree is Complete or not142
866Maximum Nesting Depth of the Parentheses Leetcode Solution142
867Check if an Array is Stack Sortable142
868Find All Possible Recipes from Given Supplies LeetCode Solution142
869LCS (Longest Common Subsequence) of three strings141
870Sum of nearest smaller and greater number141
871Tree Traversal (Preorder, Inorder & Postorder)141
872Design Browser History LeetCode Solution141
873Lemonade Change Leetcode Solution141
8744Sum141
875Daily Temperatures Leetcode Solution141
876Range sum queries without updates141
877Least Number of Unique Integers after K Removals Leetcode Solution141
878Spiral Matrix II Leetcode Solution141
879Count ways to reach the nth stair using step 1, 2 or 3141
880Rearrange Spaces Between Words Leetcode Solution141
881Matrix Chain Multiplication141
882Binary Search Tree Search and Insertion141
883Form Minimum Number From Given Sequence141
884Repeated Substring Pattern LeetCode Solution141
885Delete And Earn140
886Shortest Word Distance Leetcode Solution140
887Robot Bounded In Circle LeetCode Solution140
888GCDs of given index ranges in an array140
889Destination City Leetcode Solution140
890Maximum Score After Splitting a String Leetcode Solution140
891Construct Complete Binary Tree from its Linked List Representation140
892Find all permuted rows of a given row in a matrix140
893Distinct adjacent elements in an array140
894Diagonal Traversal LeetCode Solution140
895Best Time to Buy and Sell Stock with Transaction Fee Leetcode Solution140
896An Interesting Method to generate Binary Numbers from 1 to n140
897Count Negative Numbers in a Sorted Matrix LeetCode Solution140
898Insert Delete GetRandom140
899Count Subarrays with Same Even and Odd Elements140
900Guess Number Higher or Lower II140
901Identify and Mark Unmatched Parenthesis in an Expression139
902Special Positions in a Binary Matrix Leetcode Solution139
903Check if stack elements are pairwise consecutive139
904Check if the given array can represent Level Order Traversal of Binary Search Tree139
905Time Based Key-Value Store LeetCode Solution139
906Balanced Expression with Replacement139
907A program to check if a binary tree is BST or not139
908Sequences of given length where every element is more than or equal to twice of previous139
909Rearrange an Array Such that arr[i] is equal to i139
910Missing Element in Sorted Array LeetCode Solution139
911Find Maximum Sum Possible Equal Sum of Three Stacks139
912Number of Days Between Two Dates LeetCode Solution139
913Queries for GCD of all numbers of an array except elements in a given range139
914Set Matrix Zeroes Leetcode Solution139
915Convert Sorted List to Binary Search Tree139
916Find Common Characters Leetcode Solution138
917Minimum sum of multiplications of n numbers138
918Palindrome Partitioning Leetcode Solution138
919Range LCM Queries138
920Vertical sum in a given binary tree138
921BFS for Disconnected Graph138
922Alien Dictionary138
923Diagonal Traverse LeetCode Solution138
924Find distance between two nodes of a Binary Tree138
925Spiral Matrix III LeetCode Solution137
926Merging Intervals137
927Remove Duplicates from Sorted List II LeetCode Solution137
928Stone Game II Leetcode137
929Number of Distinct Islands Leetcode Solution137
930Analyze User Website Visit Pattern LeetCode Solution137
931Rearrange Array such that arr[i] >= arr[j] if i is even and arr[i] <= arr[j] if i is odd and j < i137
932Longest Palindromic Subsequence137
933Merge Two Sorted Lists Leetcode137
934Construct the Rectangle Leetcode Solution136
935Maximum Subarray Sum Excluding Certain Elements136
936Maximum Frequency Stack Leetcode Solution136
937Infix to Postfix136
938Three Consecutive Odds Leetcode Solution136
939Print Fibonacci sequence using 2 variables136
940Number of Equivalent Domino Pairs Leetcode Solution136
941Sliding Window Maximum136
9423 Sum136
943Averages of Levels in Binary Tree136
944Queue using Stacks136
945Can Make Arithmetic Progression From Sequence Leetcode Solution136
946Maximize Sum of Array after K Negations Leetcode Solution136
947K’th Largest Element in BST when modification to BST is not allowed136
948Intersection of Two Linked Lists LeetCode Solution136
949Lexicographical Numbers Leetcode Solution136
950Count Submatrices With All Ones LeetCode Solution135
951Binary Tree Longest Consecutive Sequence LeetCode Solution135
952Minimum Height Trees LeetCode Solution135
953Largest area rectangular sub-matrix with equal number of 1’s and 0’s135
954Difference Array | Range update query in O(1)135
955Construct BST from its given Level Order Traversal135
956Dividing Array into Pairs With Sum Divisible by K135
957All Unique Triplets that Sum up to a Given Value135
958Median of Two Sorted Arrays135
959Pattern Occurrences using Stack135
960Trim a Binary Search Tree135
961Binary array after M range toggle operations135
962Breadth First Search (BFS) for a Graph135
963Find Maximum of Minimum for Every Window Size in a Given Array134
964Height of a generic tree from parent array134
965Newman-Conway Sequence134
966Largest divisible pairs subset134
967Word Break134
968Check If a Word Occurs As a Prefix of Any Word in a Sentence Leetcode Solution134
969Largest Substring Between Two Equal Characters Leetcode Solution134
970Check if any two intervals overlap among a given set of intervals134
971Find postorder traversal of BST from preorder traversal134
972Palindrome Partitioning134
973Strongly Connected Component134
974Reverse Nodes in K-Group134
975Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space133
976Depth First Search (DFS) for a Graph133
977Product of Array Except Self LeetCode Solution133
978Split Array Into Consecutive Subsequences133
979Create Maximum Number133
980Segment Tree133
981Kth Smallest Element in a BST Leetcode Solution133
982Symmetric Tree133
983Maximum Product Subarray133
984First missing positive133
985Iterative Postorder Traversal Using Two Stacks133
986Binary Search Tree Delete Operation133
987Sign of the Product of an Array LeetCode Solution133
988Length of Longest Fibonacci Subsequence132
989The Maze III LeetCode Solution132
990Boundary Traversal of binary tree132
991Find Duplicate Subtrees132
992Asteroid Collision LeetCode Solution132
993Level Order Traversal of Binary Tree132
994Maximum subsequence sum such that no three are consecutive132
995Unique Paths II132
996My Calendar I LeetCode Solution132
997Rearrange array such that even positioned are greater than odd132
998Count pair with Given Sum132
999Climbing stairs132
1000Count Primes in Ranges132
1001Minesweeper LeetCode Solution132
1002Longest subsequence such that difference between adjacents is one131
1003Find the First Circular Tour that visits all the Petrol Pumps131
1004Serialize and Deserialize Binary Tree131
1005Double the first element and move zero to end131
1006Make The String Great Leetcode Solution131
1007Find the Difference Leetcode Solution131
1008Kill Process LeetCode Solution131
1009Longest Nice Substring LeetCode Solution131
1010Next Greater Element III LeetCode Solution131
1011K Closest Points to Origin Leetcode Solution131
1012Maximum Number of Ways to Partition an Array LeetCode Solution131
1013Decrypt String from Alphabet to Integer Mapping Leetcode Solution131
1014Partition Equal Subset Sum131
1015Find number of pairs in an array such that their XOR is 0130
1016Boolean Parenthesization Problem130
1017Maximum Length of Repeated Subarray130
1018Graph Valid Tree LeetCode Solution130
1019Insertion in a Binary Tree130
1020Super Ugly Number130
1021Largest Number Leetcode Solution130
1022The Painter’s Partition Problem130
1023Valid Boomerang Leetcode Solution130
1024Shortest Completing Word Leetcode Solution130
1025Level order traversal using two Queues130
1026Design Hit Counter LeetCode Solution129
1027Compute nCr % p129
1028Collect maximum points in a grid using two traversals129
1029Number Of Longest Increasing Subsequence129
1030Balanced Binary Tree129
1031Friends Of Appropriate Ages LeetCode Solution129
1032Count subarrays where second highest lie before highest129
1033Binary Search Tree129
1034Advantages of BST over Hash Table129
1035Ugly Number II LeetCode Solution129
1036Move all negative elements to end in order with extra space allowed128
1037Scramble String LeetCode Solution128
1038Defanging an IP Address LeetCode Solution128
1039Kth Smallest Element in a Sorted Matrix LeetCode Solution128
1040Minimum Size Subarray Sum128
1041Build an Array With Stack Operations Leetcode Solution128
1042Available Captures for Rook Leetcode Solution128
1043Maximum Product of Indexes of Next Greater on Left and Right128
1044String Matching in an Array Leetcode Solution128
1045Employee Importance LeetCode Solution128
1046Morris Inorder Traversal128
1047Number of palindromic paths in a matrix128
1048Implement Trie (Prefix Tree) Leetcode Solution128
1049Rearrange an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’128
1050Ugly Numbers128
1051Construction of Longest Increasing Subsequence (N log N)128
1052Invalid Transactions LeetCode Solution128
1053Construct Binary Tree from given Parent Array representation128
1054Regular Expression Matching Regular Expression Matching LeetCode Solution127
1055Populating Next Right Pointers in Each Node Leetcode Solution127
1056Longest Bitonic Subsequence127
1057Find whether a subarray is in form of a mountain or not127
1058Minimum Index Sum of Two Lists127
1059Maximum weight transformation of a given string127
1060Maximum Sum of 3 Non-Overlapping Subarrays127
1061Find Peak Element127
1062Maximum difference between frequency of two elements such that element having greater frequency is also greater127
1063Add two numbers127
1064Maximum length subsequence with difference between adjacent elements as either 0 or 1127
1065Count minimum steps to get the given desired array127
1066Iterative Depth First Traversal of Graph126
1067Lowest Common Ancestor126
1068Find a Peak Element II LeetCode Solution126
1069Combination Sum IV LeetCode Solution126
1070Find the minimum distance between two numbers126
1071Divisible Pairs Counting126
1072Custom Sort String Leetcode Solution126
1073Validate Binary Search Tree126
1074Bitwise AND of Numbers Range LeetCode Solution126
1075Generate Parentheses Leetcode Solution126
1076Remove Duplicates from Sorted Array II Leetcode Solution126
1077Recover Binary Search Tree Leetcode Solution126
1078Path Sum125
1079Binary Tree Data Structure125
1080Determine Whether Matrix Can Be Obtained By Rotation LeetCode Solution125
1081Largest BST Subtree LeetCode Solution125
1082Day of the Year Leetcode Solution125
1083Binary Tree Right Side View LeetCode Solution125
1084Search in Sorted Rotated Array125
1085Smallest Common Region Leetcode Solution125
1086Number of Closed Islands Leetcode Solution125
1087Path Sum II LeetCode Solution125
1088Maximize Distance to Closest Person LeetCode Solution125
1089Kth Smallest Product of Two Sorted Arrays LeetCode Solution124
1090Consecutive Characters LeetCode Solution124
1091Increasing Triplet Subsequence LeetCode Solution124
1092Rearrange array such that even index elements are smaller and odd index elements are greater124
1093Clone a Binary Tree with Random Pointers124
1094Find Smallest Range Containing Elements from k Lists124
1095Level of Each node in a Tree from source node124
1096Types of Binary Tree124
1097Subarrays with K Different Integers Leetcode Solution124
1098Number of Students Doing Homework at a Given Time Leetcode Solution124
1099Next Permutation Leetcode Solution124
1100Print all triplets in sorted array that form AP124
1101Remove Palindromic Subsequences Leetcode Solution124
1102Print Next Greater Number of Q queries124
1103Serialize and Deserialize Binary Tree LeetCode Solution123
1104Number of siblings of a given Node in n-ary Tree123
1105Count pairs from two sorted arrays whose sum is equal to a given value x123
1106Distinct Subsequences123
1107Topological Sorting123
1108Bottom View of a Binary Tree122
1109Third Maximum Number Leetcode Solution122
1110Cutting a Rod122
1111Maximum Product Subarray122
1112Constant time range add operation on an array122
1113Remove duplicates from sorted array122
1114Root to Leaf path with target sum Leetcode Solutions122
1115Find maximum difference between nearest left and right smaller elements122
1116Maximum Binary Tree121
1117Minimum Score Triangulation of Polygon Leetcode Solution121
1118Valid Tic-Tac-Toe State LeetCode Solution121
1119Find Three Element From Different Three Arrays Such That a + b + c = sum121
1120Convert BST into a Min-Heap without using array121
1121Count Largest Group Leetcode Solution121
1122Print Right View of a Binary Tree121
1123Write Code to Determine if Two Trees are Identical121
1124Construct Binary Tree from Preorder and Postorder Traversal LeetCode Solution121
1125Mean of Array After Removing Some Elements Leetcode Solution121
1126Minimum Absolute Difference in BST Leetcode Solution120
1127Search an Element in Sorted Rotated Array120
1128Iterative method to find ancestors of a given binary tree120
1129Reformat The String Leetcode Solution120
1130Products of ranges in an array120
1131Palindrome Permutation LeetCode Solution120
1132Search Insert Position120
1133Longest Subarray of 1’s After Deleting One Element LeetCode Solution120
1134Golomb sequence120
1135Queries for Number of Distinct Elements in a Subarray120
1136Cells with Odd Values in a Matrix LeetCode Solution120
1137Minimum sum of squares of character counts in a given string after removing k characters120
1138Closest Binary Search Tree Value Leetcode Solution119
1139Longest Increasing Consecutive Subsequence119
1140Thousand Separator Leetcode Solution119
1141Moser-de Bruijn Sequence119
1142Red-Black Tree Introduction119
1143Prime Palindrome LeetCode Solution119
1144Sum of Even Numbers After Queries119
1145Construct K Palindrome Strings LeetCode Solution119
1146Print modified array after executing the commands of addition and subtraction119
1147Find a sorted subsequence of size 3 in linear time119
1148Binary Tree to Binary Search Tree Conversion118
1149Transform a BST to Greater sum Tree118
1150Delete Nodes and Return Forest Leetcode Solution118
1151Factorial Trailing Zeroes LeetCode Solution118
1152Maximum Product of Splitted Binary Tree LeetCode Solution118
1153Merge two BSTs with limited extra space118
1154Find maximum length Snake sequence118
1155Bus Routes Leetcode Solution118
1156Swap Nodes In Pairs117
1157K’th Largest element in BST using constant extra space117
1158Palindromic Substrings Leetcode Solution117
1159Possible Bipartition LeetCode Solution117
1160Number of Orders in the Backlog Leetcode Solution117
1161Longest Repeated Subsequence117
1162Find Two Non-overlapping Sub-arrays Each With Target Sum LeetCode Solution117
1163K maximum sums of overlapping contiguous sub-arrays117
1164Check Array Formation Through Concatenation Leetcode Solution117
1165Decision Tree117
1166Kth Smallest Number in Multiplication Table Leetcode Solution117
1167Count even length binary sequences with same sum of first and second half bits117
1168Find the smallest binary digit multiple of given number117
1169Swapping Nodes in a Linked List Leetcode Solution116
1170Minimum Sideway Jumps LeetCode Solution116
1171Priority Queue116
1172Web Crawler LeetCode Solution116
1173Compare Strings by Frequency of the Smallest Character Leetcode Solution116
1174Minimum Moves to Equal Array Elements LeetCode Solution116
1175Subset Sum Problem in O(sum) space116
1176Maximize sum of consecutive differences in a circular array116
1177Minimum Cost to Move Chips to The Same Position LeetCode Solution116
1178Rotate Array116
1179Search Suggestions System LeetCode Solution115
1180Closest Leaf in a Binary Tree LeetCode Solution115
1181Find Largest Value in Each Tree Row LeetCode Solution115
1182First Bad Version115
1183Given a binary tree, how do you remove all the half nodes?114
1184Decrease Elements To Make Array Zigzag LeetCode Solution114
1185Remove Max Number of Edges to Keep Graph Fully Traversable Leetcode Solution114
1186Queue Reconstruction by Height114
1187Diameter of N-Ary Tree LeetCode Solution114
1188Count Pairs Whose Products Exist in Array114
1189Contiguous Array LeetCode Solution113
1190Maximum number of segments of lengths a, b and c113
1191Convert Sorted Array to Binary Search Tree LeetCode Solutions113
1192Moving Stones Until Consecutive Leetcode Solution113
1193Reverse a Path in BST using Queue113
1194Kth Smallest Element in a BST113
1195Matchsticks to Square Leetcode Solution113
1196Write a function to get the intersection point of two Linked Lists112
1197How to print maximum number of A’s using given four keys112
1198Lowest Common Ancestor in Binary Search Tree112
1199Integer Break LeetCode Solution112
1200Champagne Tower LeetCode Solution112
1201Array Queries for multiply replacements and product112
1202Valid Triangle Number112
1203Maximum sum bitonic subarray112
1204Sum of Left Leaves LeetCode Solution112
1205Maximum Depth Of Binary Tree112
1206Reformat Date LeetCode Solution112
1207Filter Restaurants by Vegan-Friendly, Price and Distance Leetcode Solution112
1208Range Sum Query using Sparse Table111
1209Range Queries for Longest Correct Bracket Subsequence111
1210New 21 Game111
1211Replace two consecutive equal values with one greater111
1212Maximum sum of pairs with specific difference111
1213Maximum Value at a Given Index in a Bounded Array LeetCode Solution110
1214Path Crossing Leetcode Solution110
1215Convert Integer to the Sum of Two No-Zero Integers Leetcode Solution110
1216Symmetric Tree LeetCode Solution Leetcode Solution110
1217Graph and its representation110
1218Valid Perfect Square LeetCode Solution110
1219Divide Two Integers Leetcode Solution110
1220Concatenation of Array LeetCode Solution110
1221Design Skiplist LeetCode Solution110
1222Guess The Word110
1223Check for Identical BSTs without building the trees109
1224Lowest Common Ancestor of a Binary Tree Leetcode Solution109
1225Maximum sum of a path in a Right Number Triangle109
1226Check Completeness of a Binary Tree LeetCode Solution109
1227BST to a Tree with Sum of all Smaller Keys109
1228Check if each internal node of a BST has exactly one child109
1229Print modified array after multiple array range increment operations109
1230The kth Factor of n Leetcode Solution109
1231Arithmetic Slices II – Subsequence LeetCode Solution109
1232Perfect Squares LeetCode Solution109
1233Flatten 2D Vector LeetCode Solution109
1234Merge Sort109
1235Longest Common Prefix Using Word by Word Matching108
1236LRU Cache Leetcode Solution108
1237Parallel Courses II LeetCode Solution108
1238Check if all levels of two Binary Tree are anagrams or not108
1239Sliding Window Median Leetcode Solution108
1240Count Subsets Having Distinct Even Numbers108
1241Minimum Swaps To Make Sequences Increasing LeetCode Solution108
1242Queries on Probability of Even or Odd Number in given Ranges108
1243Power of Two108
1244Graph Cloning107
1245Missing Number107
1246Count and Toggle Queries on a Binary Array107
1247Image Overlap LeetCode Solution107
1248Find Minimum in Rotated Sorted Array II LeetCode Solution107
1249Largest Plus Sign Leetcode Solution107
1250Maximum Array from Two given Arrays Keeping Order Same107
1251Maximize Elements Using Another Array107
1252Mean of range in array107
1253Contiguous Array107
1254Check If a String Can Break Another String Leetcode Solution106
1255Bold Words in String LeetCode Solution106
1256Print n terms of Newman-Conway Sequence106
1257Maximum Product Subarray106
1258Find minimum number of merge operations to make an array palindrome106
1259Verify Preorder Serialization of a Binary Tree105
1260Minimum Remove to Make Valid Parentheses LeetCode Solution105
1261Excel Sheet Column Title LeetCode Solution105
1262Find k-th smallest element in BST (Order Statistics in BST)105
1263Merge k Sorted Lists Leetcode Solution104
1264Print Ancestors of a Given Binary Tree Node Without Recursion104
1265Next greater element104
1266Minimum Time to Collect All Apples in a Tree LeetCode Solution103
1267Palindrome Partitioning103
1268Smallest Range II Leetcode Solution103
1269Min Cost Climbing Stairs LeetCode Solution103
1270Check if two nodes are on the same path in a Tree102
1271Merge Sorted Array101
1272Orderly Queue LeetCode Solution101
1273Check in binary array the number represented by a subarray is odd or even101
1274Koko Eating Bananas LeetCode Solution100
1275Peeking Iterator LeetCode Solution100
1276Check if X can give change to every person in the Queue99
1277Different Ways to Add Parentheses Leetcode Solution99
1278Newman–Shanks–Williams prime99
1279Number of elements less than or equal to a given number in a given subarray99
1280Largest Submatrix With Rearrangements LeetCode Solution97
1281Maximum Sum Increasing Subsequence97
1282Find maximum average subarray of k length97
1283Range Minimum Query (Square Root Decomposition and Sparse Table)97
1284Longest Substring Without Repeating Characters Leetcode Solution97
1285Queries for Decimal Values of Subarrays of a Binary Array96
1286Number of indexes with equal elements in given range96
1287Array Nesting Leetcode Solution95
1288Minimum Total Space Wasted With K Resizing Operations LeetCode Solution95
1289Maximum product of an increasing subsequence95
1290Check given array of size n can represent BST of n levels or not94
1291Binary Tree to Binary Search Tree Conversion using STL set94
1292Arranging Coins Leetcode Solution93
1293Minimum Number of People to Teach LeetCode Solution93
1294Find the Winner of the Circular Game LeetCode Solution92
1295Jump Game IV LeetCode Solution92
1296Reach a Number LeetCode Solution92
1297Queries on XOR of greatest odd divisor of the range92
1298Convert to Base -2 LeetCode Solution92
1299Encoded String With Shortest Length LeetCode Solution92
1300Random Pick Index LeetCode Solution92
1301Minimum Possible Integer After at Most K Adjacent Swaps On Digits LeetCode Solution91
1302Convert a BST to a Binary Tree such that sum of all greater keys is added to every key91
1303Insert Delete GetRandom O(1) Leetcode Solution90
1304Palindrome Number LeetCode Solution88
1305Number of Subsequences That Satisfy the Given Sum Condition LeetCode solution88
1306Vertical Order Traversal of Binary Tree LeetCode Solution87
1307Add Two Numbers II Leetcode Solution87
1308Design Underground System Leetcode Solution86
1309Continuous Subarray Sum LeetCode Solution85
1310Print Maximum Length Chain of Pairs84
1311Detect Capital Leetcode Solution81
1312Design A Leaderboard Leetcode Solution80
1313Top K Frequent Elements LeetCode Solution79
1314Substring with Concatenation of All Words Leetcode Solution78
1315Minimum Swaps to Group All 1’s Together Leetcode Solution77
1316Decode String Leetcode Solution74
1317Minimum Path Sum Leetcode Solution74
1318Odd Even Linked List Leetcode Solution72
1319Binary Tree Inorder Traversal LeetCode Solution72
1320Count Sub Islands LeetCode Solution72
1321Shortest Unsorted Continuous Subarray LeetCode Solution71
1322Shifting Letters LeetCode Solution71
1323Find the Town Judge LeetCode Solution70
1324Sum Root to Leaf Numbers LeetCode Solution70
1325Best Meeting Point LeetCode Solution70
1326Maximum Population Year LeetCode Solution70
1327Longest Common Subsequence LeetCode Solution68
1328Find the Town Judge LeetCode Solution68
1329Design Add and Search Words Data Structure LeetCode Solution67
1330Rectangle Overlap LeetCode Solution65
1331Score of Parenthesis LeetCode Solution65
1332Maximum Population Year LeetCode Solution65
1333Flatten Binary Tree to Linked List LeetCode Solution62
1334Stone Game IV LeetCode Solution62
1335Insert into a Sorted Circular Linked List LeetCode Solution62
1336Is Graph Bipartite? LeetCode Solution60
1337Range Sum Query 2D – Immutable LeetCode Solution60
1338Valid Triangle Number LeetCode Solution59
1339Reveal Cards In Increasing Order Leetcode Solution55
1340Divide Chocolate LeetCode Solution50
1341Range Sum of BST LeetCode Solution43
1342Step-By-Step Directions From a Binary Tree Node to Another LeetCode Solution42
1343Reverse Integer Leetcode Solution41
1344Sort Colors LeetCode Solution37
1345Excel Sheet Column Number LeetCode Solution34
1346Find K Closest Elements LeetCode Solution34
1347Rotate String LeetCode Solution32
1348Maximum Side Length of a Square with Sum Less than or Equal to Threshold LeetCode Solution31
Translate »