Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution

Difficulty Level Hard
Frequently asked in Affirm Amazon Apple Bloomberg Facebook Google HRT LinkedIn YelpViews 3

Problem Statement:

Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution: RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element.

Implement the RandomizedCollection class:

  • RandomizedCollection() Initializes the empty RandomizedCollection object.
  • bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise.
  • bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.
  • int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of same values the multiset contains.

You must implement the functions of the class such that each function works on average O(1) time complexity.

Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection.

Examples:

Input

["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"]
[[], [1], [1], [2], [], [1], []]

Output

[null, true, false, true, 2, true, 1]

Explanation

RandomizedCollection randomizedCollection = new RandomizedCollection();
randomizedCollection.insert(1);   // return true since the collection does not contain 1.
                                  // Inserts 1 into the collection.
randomizedCollection.insert(1);   // return false since the collection contains 1.
                                  // Inserts another 1 into the collection. Collection now contains [1,1].
randomizedCollection.insert(2);   // return true since the collection does not contain 2.
                                  // Inserts 2 into the collection. Collection now contains [1,1,2].
randomizedCollection.getRandom(); // getRandom should:
                                  // - return 1 with probability 2/3, or
                                  // - return 2 with probability 1/3.
randomizedCollection.remove(1);   // return true since the collection contains 1.
                                  // Removes 1 from the collection. Collection now contains [1,2].
randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.

Approach:

Idea:

The data structure can be implemented with the help of a Hash_map consisting of a pair of <int, Hash_set> and an arrayList. The Hash_map will store the indices of the elements and the list will store the list of elements present so far. The required methods can be implemented as follows:

  • insert: Insert the element to the list and add the index to HashMap[element].
  • remove: First, we find any index of the element to be removed in the HashMap. Now we will update the element in this index with the last element of the list. Since the last element of the list has been assigned a new index, we have to update its value in the HashMap. We also have to get rid of the index of the element we removed from the HashMap.
  • getRandom: Just sample a random element from the list.

Code for Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution:

C++ Solution:

class RandomizedCollection {
public:
    unordered_map<int,unordered_set<int>> mp;
    vector<int> arr;
    int size = 0;
    
    RandomizedCollection() {
        
    }
    
    bool insert(int val) {
        bool status = not mp.count(val);
        mp[val].insert(size);
        arr.push_back(val);
        size++;
        return status;
    }
    
    bool remove(int val) {
        bool status = mp.count(val);
        if(status){
            int last_element = arr.back();
            if(val == last_element){
                mp[val].erase(arr.size()-1);
                arr.pop_back();
                size--;
                if(mp[val].size()==0)
                    mp.erase(val);
            }
            else{
                int index;
                for(auto it:mp[val]){
                    index = it;
                    break;
                }
                arr[index] = last_element;
                mp[last_element].erase(arr.size()-1);
                arr.pop_back();
                size--;
                mp[val].erase(index);
                mp[last_element].insert(index);
                if(mp[val].size()==0)
                    mp.erase(val);
            } 
        }
        return status;
    }
    
    int getRandom() {
        return arr[rand()%arr.size()];
    }
};

/**
 * Your RandomizedCollection object will be instantiated and called as such:
 * RandomizedCollection* obj = new RandomizedCollection();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */

Complexity Analysis of Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution:

  • Time Complexity: The time complexity of the above code is O(n) with n being the number of operations.
  • Space ComplexityThe space complexity of the above code is O(n).

Top Interview Questions

S.No Interview Question Number of times has been asked
1Delete a node in doubly linked list2828
2Java program to find the number of Nodes in a Binary Tree2508
3Reverse a string without affecting special characters2468
4Delete a node of a linked list at given position1982
5Palindrome using Recursion1881
6Insert nodes in a linked list in a sorted way (Ascending Order)1668
7Find elements pair from array whose sum equal to number1655
8Sort Elements by Frequency of Occurrences1638
9Write a program to print all permutations of a given string1613
10Find Minimum Distance Between Two Numbers in an Array1479
11Create a Doubly Linked List1452
12Quick Sort1424
13Reverse an Array1417
14Smallest window in a string containing all characters of another string1401
15Find a Triplet That Sum to a Given Value1364
16Recursively remove all adjacent duplicates1361
17First Repeating Element1346
18Arrange Even and Odd number such that Odd comes after Even1325
19Sum of numbers in String1324
20Smallest Positive Number Missing in an Unsorted Array1291
21Check if the Elements of an Array are Consecutive1260
22Detect a loop in the Linked List1245
23Largest Sum Contiguous Subarray1235
24Quick Sort on SIngly Linked List1221
25Subarray with Given Sum1217
26Print all Possible Combinations of R Elements in a given Array of size N1208
27Recursive function to do substring search1204
28Find the Maximum Repeating Number in Array1160
29Binary Tree Level order traversal in Java1130
30Find the First and Second Smallest Elements1126
31Check if two linked lists are identical1112
32Maximum Subarray Sum using Divide and Conquer1107
33Remove characters from first string which are in second1075
34Find Leaders in an Array1064
35Swap nodes in the linked list1041
36Find the Number Occurring Odd Number of Times in an Array1008
37Arrange given Numbers to Form the Biggest Number II996
38Find the second most frequent character992
39Given a string find its first non-repeating character975
40Find Triplet in Array With a Given Sum968
41Total number of occurrences of a given item in the linked list959
42Given a sorted array and a number x, find the pair in array whose sum is closest to x959
43A Program to check if strings are rotations of each other or not952
44Print all possible words from phone digits939
45Find the Missing Number929
46Rearrange Positive and Negative Numbers Alternatively in Array925
47Longest Palindromic Substring909
48Segregate even and odd nodes in a linked list891
49Print Longest common subsequence887
50Union and Intersection of Two Linked Lists879
51Transform one string to another using minimum number of given operations873
52Check rearranged string can form a palindrome854
53Rearrange given Array in Maximum Minimum Form851
54Count Possible Triangles824
55Iterative Implementation of Quick Sort823
56Multiplication of Two Matrices808
57Check if the linked list is palindrome801
58Count of Triplets With Sum Less than Given Value800
59Rotate a Linked List799
60Stock Buy Sell to Maximize Profit797
61Concatenation of two strings768
62Tug of War766
63Print all duplicates in the input string762
64Count Number of Substrings with K Distinct Character’s761
65Find Nearest Greater and Smaller Element750
66Find Pythagorean Triplets from Array742
67The Celebrity Problem742
68Reverse String Without Temporary Variable736
69Remove ‘b’ and ‘ac’ from a given string736
70Find all Common Elements in Given Three Sorted Arrays734
71Remove all duplicates in an unsorted linked list714
72Find the Row with Maximum Number of 1’s712
73Find the Peak Element from an Array704
74Find the subarray whose sum is equal to a given number X700
75Remove Minimum Characters so that Two Strings Become Anagrams696
76Addition of Two Matrices691
77Find Smallest Missing Number in a Sorted Array691
78A Product Array Puzzle689
79Insertion Sort689
80Generate all Binary Strings Without Consecutive 1’s681
81Implement Two Stacks in an Array681
82Maximum Sum of Non Consecutive Elements674
83Maximum Product Subarray II661
84Lexicographic rank of string660
85Check if Two given Matrices are Identical653
86Multiplication of Previous and Next652
87Subtraction of Two Matrices640
88Merge K Sorted Arrays and Print Sorted Output636
89Move All the Zeros to the End of the Given Array635
90Divide a string in N equal parts629
91Form Minimum Number from Given Sequence of D’s and I’s628
92Online Algorithm for Checking Palindrome in a Stream628
93Remove recurring digits in a given number622
94Check whether two strings are anagram of each other621
95Maximum Circular Subarray Sum616
96Sort a linked list that is sorted alternating ascending and descending613
97Sort a stack using a temporary stack613
98Find the Minimum Element in a Sorted and Rotated Array610
99Move last element of the Linked List at first place608
100Subarray and Subsequence605
101First Circular Tour to Visit all the Petrol Bunks603
102Largest Subarray with Equal Number of 0’s and 1’s602
103Flattening a linked list599
104Compare two strings(linked lists)599
105Maximum Element in an Array which is Increasing and then Decreasing595
106Palindrome Permutations of a String591
107Elements Appear more than N/K times in Array584
108Palindromes in a given range583
109Run length encoding581
110Majority Element581
111Print all permutations with repetition579
112Minimum insertions to form a shortest palindrome576
113Pangram Checking576
114Minimum Characters to be Added at Front to Make String Palindrome570
115Merge a linked list into another at alternate positions570
116Remove all duplicates in a sorted linked list569
117Most repeating character in a string568
118Minimum number of Merge Operations to make an Array Palindrome567
119Rearrange a given linked list in-place567
120Rotate string to get lexicographically minimum string563
121Repeated Subsequence of Length Two or More561
122Print all anagrams together in a sequence of words558
123Reorder an Array According to the Given Indexes556
124Pancake Sorting Problem546
125Two Sum Leetcode Solution543
126Merge Overlapping Intervals II542
127Clone a Linked List with next and random pointer541
1283Sum Leetcode Solution539
129Transpose of a Matrix533
130Size of The Subarray With Maximum Sum530
131Remove Extra Spaces from a String529
132Removing Spaces from a String using stringstream527
133Remove duplicates from a string525
134Partition Problem523
135Smallest Palindrome after Replacement523
136Check if a given string is a rotation of a palindrome523
137Maximum Sum Increasing Subsequence522
138Longest Palindrome can be Formed by Removing or Rearranging Characters520
139Check whether Strings are K Distance Apart or Not512
140Generate all Binary Strings from Given Pattern508
141Find Zeros to be Flipped so that Number of Consecutive 1’s is Maximized506
142Length of Longest valid Substring506
143Insert Node in the Sorted Linked List505
144Delete Last Occurrence504
145Check if Two given Strings are Isomorphic to each other499
146Maximum difference between two elements such as larger element comes after smaller494
147Program to Toggle all Characters in a String492
148Given string is interleaving of two other strings or not489
149Count Minimum Steps to Get the given Array484
150Merge sort better than quick sort for linked lists482
151Number of Smaller Elements on Right Side481
152Check length of a String is Equal to the Number Appended at its Last479
153Find Pair with Given Difference478
154Check if all Rows of a Matrix are Circular Rotations of Each Other477
155Longest Common Prefix using Divide and Conquer474
156Find nth node of the Linked list from the end473
157Find a Fixed Point in a Given Array467
158Sort 0s 1s and 2s in an Array466
159Print all interleavings of given two strings464
160Compare Two Version Numbers463
161Reverse words in a given string462
162Find the Subarray of given length with Least Average461
163Reorder Array Using Given Indexes459
164Merge two sorted linked lists such that merged list is in reverse order458
165Print Reverse of a string (Recursion)457
166Split linked list using alternate nodes457
167Median of Two Sorted Arrays LeetCode Solution456
168Print string of odd length in ‘X’ format445
169Find K Length Subarray of Maximum Average440
170Find Element Using Binary Search in Sorted Array439
171Print all Palindromic Partitions of a String438
172Swap Kth Node from beginning with Kth Node from End437
173Find Duplicates in an Array in Most Efficient Way432
174print all palindromic partitions425
175Flatten a multilevel linked list422
176Maximum Length of Chain Pairs420
177Shortest Superstring Problem420
178Check if String Follows Order of Characters by a Pattern or not417
179Sorting a K Sorted Array413
180Sort a String According to Another String410
181Longest Span with same Sum in two Binary Arrays II404
182Reverse a Linked List in groups401
183Find a Sorted Subsequence of size 3400
184Program to add two binary digits397
185Recursively print all the sentences that can be formed from list of word lists397
186Find the two Numbers with Odd Occurrences in an Unsorted Array393
187Longest Common Prefix Using Binary Search II390
188Reverse a Singly Linked List (Iterative/Non-Recursive)389
189Caesar Cipher387
190Kth Non-repeating Character385
191Rearrange a linked list in Zig-Zag384
192Check if String can Become Empty by Recursively Deleting given Substring383
193Longest Common Prefix Word by Word Matching380
194Pancake Sorting380
195Rotate Image by 90 degrees380
196Permutations of a Given String Using STL373
197Perfect Reversible String371
198Merging Two Sorted Arrays368
199Increasing Subsequence of Length three with Maximum Product368
200Find First non-repeating character in a string365
2011`s and 2`s complement of binary number365
202Sort a linked list with 0s, 1s and 2s365
203Find the point where a monotonically increasing function becomes positive first time364
204Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes363
205Four Elements that Sum to Given362
206List items containing all characters of a given word358
207Delete N nodes after M357
208Longest Common Prefix using Character by Character Matching353
209Count Number of Occurrences in a Sorted Array351
210Palindrome string (number)347
211Split a string347
212Minimum Characters to be Removed to Make a Binary String Alternate343
213Recursive Implementation of atoi()341
214Check if a Linked list of Strings form a Palindrome339
215Print All Distinct Elements of the Array337
216Sorting the array of strings336
217Even Substring Count336
218Convert a String that is Repetition of a Substring of Length K333
219Maximum occurring character in a string332
220Valid Parentheses LeetCode Solution332
221Reverse a singly linked list recursively331
222Find the first Repeating Number in a Given Array331
223Print Shortest Path to Print a String on Screen329
224Can we reverse a linked list in less than O(n) time ?327
225Binary Tree to Doubly linked list326
226wildcard character matching325
227Convert string1 to string2 in one edit325
228Reverse a String using Stack324
229Nth Character in Concatenated Decimal String323
230Maximum Subarray Leetcode Solution321
231Sort Elements by Frequency II321
232Count the number of words318
233Lower Case To Upper Case318
234Split Four Distinct Strings315
235Merge Two Sorted Arrays315
236Find the Lost Element From a Duplicated Array313
237Find middle of the Linked List311
238Longest Common Subsequence with Permutations309
239Count the Pairs at Same Distance as in English Alphabets306
240Matrix Chain Multiplication using Dynamic Programming302
241Next Greater Element in an Array300
242Palindrome Permutation294
243Roman to Integer Leetcode Solution291
244Find All Pairs With a Given Difference290
245Find Nth Node288
246Triplet from three linked lists with given sum286
247Searching a node in a Binary Search Tree285
248String(represents an integer) to value283
249Delete a Tree283
250Reverse a String282
251Word Search Leetcode Solution281
252Reverse Bits281
253Delete a node under given conditions280
254Print all Possible Ways to Break a String in Bracket Form280
255Binary Tree278
256Change Gender of a given String278
257How to Efficiently Implement k Stacks in a Single Array?275
258Sort an array of strings275
259First non Repeating Element274
260Meeting Rooms II LeetCode Solution271
261Longest Common Extension271
262Count Pairs With Given Sum271
263Toeplitz Matrix270
264Number of sub-strings which recursively add up to 9270
265Remove middle points in a linked list of line segments270
266Repeated Substring Pattern269
267Move all negative elements to one side of array267
268Longest Palindromic Substring LeetCode Solution266
269Remove spaces from a string266
270N queen problem265
271Shuffle a given Array264
272Min Stack262
273Cuckoo sequence program259
274Number of Islands LeetCode Solution258
275Dijkstra Algorithm257
276Max stack256
277House Robber Leetcode Solution254
278Find, second, frequent, character254
279Most Frequent Element in an Array254
280Minimize the maximum difference between the heights253
281Clone a linked list with next and random pointer (Hashing)252
282Search Insert Position Leetcode Solution251
283Expression Evaluation250
284Fibonacci numbers250
285Sort linked which is sorted on absolute values249
286Sudoku Solver247
287Valid Palindrome Leetcode Solution247
288KMP Algorithm246
289Plus One Leetcode Solution246
290Subset Leetcode246
291Number Of 1 bits245
292Reverse words in a string244
293Combination Sum Leetcode Solution244
294How to Delete a Linked List244
295Min Stack Leetcode Solution243
296Evaluation of Postfix Expression242
297Word Search241
298Backspace String Compare238
299Set Matrix Zeroes237
300Sqrt(x) Leetcode Solution236
301Merge Sorted Arrays Leetcode Solution235
302Reversing a Queue234
303Pair of Positive Negative Values in an Array234
304Rabin Karp Algorithm234
305Subarray with 0 sum233
306Common elements in all rows of a given matrix232
307Tower Of Hanoi230
308Delete middle element of a stack230
309Contains Duplicate II Leetcode Solution230
310Product of array except self229
311Combination Sum228
312Intersection of Two Arrays II Leetcode Solution227
313String Compression227
314Integer to Roman Leetcode Solution227
315Pascal Triangle Leetcode227
316Reverse individual words225
317Count subarrays with equal number of 1’s and 0’s225
318Count of index pairs with equal elements in an array224
319Bellman Ford Algorithm224
320Minimum swaps required to bring all elements less than or equal to k together224
321Sliding Window Technique223
322Find Top K (or Most Frequent) Numbers in a Stream222
323Implementation of Deque using Doubly Linked List222
324Construct Binary Tree from Given Inorder and Preorder Traversals222
325Single Number Leetcode Solution222
326Arithmetic Expression Evaluation221
327Add Binary Leetcode Solution221
328Contains Duplicate220
329Minimum Value to Get Positive Step by Step Sum Leetcode Solution220
330Page Replacement Algorithms in Operating Systems219
331Segregate even and odd numbers219
332Second Most Repeated Word in a Sequence219
333Palindrome Linked List Leetcode Solution219
334Sort elements by frequency219
335Pow(x, n) Leetcode Solution218
336Postfix to Infix Conversion218
337Find sum of non-repeating elements (distinct) elements in an array218
338Design a stack that supports getMin() in O(1) time and O(1) extra space217
339Group Words With Same Set of Characters217
340Next Permutation216
341Count Odd Numbers in an Interval Range Leetcode Solution216
342Kruskal Algorithm216
343Maximum Number of Balloons Leetcode Solution216
344Third Maximum Number Leetcode Solution215
345Smallest Subarray with k Distinct Numbers214
346Sum of minimum and maximum elements of all subarrays of size k213
347Top K Frequent Words213
348Convex Hull Algorithm213
349Longest Substring Without Repeating Characters LeetCode Solution213
350Permutations Leetcode Solution213
351Find Lucky Integer in an Array Leetcode Solution212
352K-th Smallest Element in a Sorted Matrix212
353Find the Town Judge Leetcode Solution211
354Sorting array using Stacks211
355Longest Common Prefix Leetcode Solution210
356Find Numbers with Even Number of Digits Leetcode Solution210
357Majority Element Leetcode Solution210
358Maximum Subarray210
359Scramble String210
360Count subarrays having total distinct elements same as original array209
361First element occurring k times in an array209
362Minimum operation to make all elements equal in array209
363Spiral Matrix LeetCode Solution208
364Evaluate Division208
365Swap Nodes in Pairs Leetcode Solutions207
366Huffman Coding207
367Special Number207
368Given two unsorted arrays find all pairs whose sum is x207
369Number of Good Pairs Leetcode Solution206
370Prefix to Infix Conversion206
371Minimum Path Sum206
372Check if two arrays are equal or not206
373Missing Number Leetcode Solution206
374Pascal’s Triangle II Leetcode Solution206
375Search in Rotated Sorted Array Leetcode Solution205
376Best Time to Buy and Sell Stock  II Leetcode Solution205
377Merge Two Sorted Lists Leetcode Solutions205
378Count Primes Leetcode Solutions205
379Sort Array by Increasing Frequency Leetcode Solution204
380Find duplicates in a given array when elements are not limited to a range204
381Reversing the First K elements of a Queue204
382Reverse a Number Using Stack204
383Single Number204
384Group Anagrams203
385Minimum Absolute Difference Leetcode Solution203
386Maximal Square203
387House Robber II Leetcode Solution202
388Power of Two Leetcode Solution202
389Find All Numbers Disappeared in an Array Leetcode Solution202
390Top K Frequent Elements202
391Minimum Steps to reach target by a Knight202
392Sorting using trivial hash function201
393Matrix Diagonal Sum Leetcode Solution201
394Fizz Buzz Leetcode201
395Unique Paths Leetcode Solution201
396Maximum possible difference of two subsets of an array201
397Running Sum of 1d Array Leetcode Solution201
398Maximum Distance Between two Occurrences of Same Element in Array201
399Find Minimum In Rotated Sorted Array200
400Expression Contains Redundant Bracket or Not199
401Zigzag Conversion199
402How Many Numbers Are Smaller Than the Current Number Leetcode Solution199
403Convert String To Int199
404Average Salary Excluding the Minimum and Maximum Salary Leetcode Solution199
405Range Sum Query 2D – Immutable Leetcode Solution199
406How to Implement Stack Using Priority Queue or Heap?199
407Leetcode Permutations198
408Find the Closest Palindrome number198
409Coin Change 2 Leetcode Solution198
410Max Consecutive Ones Leetcode Solution198
411Subarray Sum Equals k198
412Happy Number Leetcode Solution198
413Unique Paths198
414Sort Integers by The Number of 1 Bit Leetcode Solution198
415Difference between highest and least frequencies in an array197
416Decode String197
417Letter Case Permutation197
418Smallest Element Repeated Exactly K Times197
419Find the first repeating element in an array of integers197
420Find Number of Employees Under every Employee197
421Subset sum problem196
422Remove Duplicates from Sorted Array Leetcode Solution196
423Find Winner on a Tic Tac Toe Game Leetcode Solution196
424Cumulative Frequency of Count of Each Element in an Unsorted Array196
425Length of the largest subarray with contiguous elements196
426Subarray Sum Equals K LeetCode Solution196
427Check if Array Contains Contiguous Integers With Duplicates Allowed196
428Reverse Integer196
429Palindrome Substring Queries196
430Monotonic Array LeetCode Solution195
431Find top three repeated in array195
432Sort a stack using recursion195
433Implement Stack and Queue using Deque195
434Capacity To Ship Packages Within D Days Leetcode Solution194
435Count Substrings with equal number of 0s, 1s and 2s194
436Fibonacci Number LeetCode Solution194
437Nth Catalan Number194
438Reverse Vowels of a String Leetcode Solution194
439Best Time to Buy and Sell Stock III Leetcode Solution194
440Reverse a Stack Using Recursion193
441Find Median from data Stream193
442Print All Distinct Elements of a Given Integer Array193
443Reverse Words in a String III LeetCode Solution193
444Find The Duplicate Number193
445Subtract the Product and Sum of Digits of an Integer Leetcode Solution193
446Sum of Subarray Ranges Leetcode Solution193
447Maximum Depth of Binary Tree Leetcode Solution193
448Shuffle the Array Leetcode Solution192
449Bipartite Graph192
450LRU Cache Implementation192
451Check If N and Its Double Exist Leetcode Solution192
452Delete a Node from linked list without head pointer192
453Trapping Rain Water Leetcode Solution192
454Prim’s Algorithm192
455Integer to English words191
456Generate a String With Characters That Have Odd Counts Leetcode Solution191
457Find the Duplicate Element191
458Merge Two Sorted Linked Lists191
459Subarrays with distinct elements191
460Sorting a Queue without Extra Space190
461Priority Queue Using Singly Linked List190
462Find Common Characters Leetcode Solution190
463Target Sum190
464Reverse a String190
465Kth largest element in an Array Leetcode Solutions190
466Excel Sheet Column Number Leetcode Solution190
467Print all subarrays with 0 sum189
468Iterative Tower of Hanoi189
469Balanced Binary Tree Leetcode Solution189
470Longest Common Subsequence189
471Find all pairs (a, b) in an array such that a % b = k189
472Edit Distance188
473Concatenation of Array LeetCode Solution188
474Fizz Buzz188
475Count pairs from two linked lists whose sum is equal to a given value188
476Find the Difference Leetcode Solution188
477Minimum Moves to Equal Array Elements Leetcode Solution188
478Kids With the Greatest Number of Candies Leetcode Solution188
479The K Weakest Rows in a Matrix Leetcode Solution187
480Kth Largest Element in a Stream Leetcode Solution187
481Floyd Warshall Algorithm187
482Remove Minimum Number of Elements Such That no Common Element Exist in both Array187
483Find First and Last Position of Element in Sorted Array Leetcode Solution187
484Word Ladder LeetCode Solution187
485Find elements which are present in first array and not in second187
486Degree of an array186
487Longest Common Prefix using Trie186
488Find subarray with given sum (Handles Negative Numbers)186
489Text Justification LeetCode Solution186
490Count and Say186
491Next Greater Element I Leetcode Solution186
492Design Parking System Leetcode Solution186
493Number of Steps to Reduce a Number to Zero Leetcode Solution186
494Merge Overlapping Intervals185
495MiniMax Algorithm185
496Multiply Strings Leetcode Solution185
497Prefix to Postfix Conversion185
498Flood Fill LeetCode185
499Zigzag Conversion LeetCode Solution185
500Count and Say Leetcode Solution185
501Reverse a linked list184
502Shortest Palindrome184
503Top View of Binary Tree183
504Slowest Key Leetcode Solution183
505Max Area of Island183
506Pair with given product183
507Convert array into Zig-Zag fashion183
508Length of Last Word Leetcode Solution183
509Find four elements that sum to a given value (Hashmap)183
510The Stock Span Problem183
511Substring With Concatenation Of All Words183
512Mobile Numeric Keypad Problem183
513Recursion183
514Longest subarray not having more than K distinct elements183
515Priority Queue in C++183
516Jump Game Leetcode Solution183
517Move Zeroes LeetCode Solution183
518Valid Parenthesis String183
519Peak Index in a Mountain Array183
520Find N Unique Integers Sum up to Zero Leetcode Solution183
521Next Greater Frequency Element183
522Iterative Inorder Traversal of a Binary Tree182
523Shuffle String Leetcode Solution182
524Find distinct elements common to all rows of a matrix182
525Check if a given array contains duplicate elements within k distance from each other182
526Implement a stack using single queue182
527Longest Common Prefix using Sorting182
528Intersection of Two Arrays182
529Find any one of the multiple repeating elements in read only array181
530Find missing elements of a range181
531Postfix to Prefix Conversion181
532Last Stone Weight181
533Find Index of Closing Bracket for a Given Opening Bracket in an Expression181
534Count number of triplets with product equal to given number181
535Contiguous Array Leetcode180
536Relative Sort Array Leetcode Solution180
537Koko Eating Bananas Leetcode Solution180
538Delete Node in a Linked List Leetcode Solution180
539Smallest Subarray With all Occurrences of a Most Frequent Element179
540Implement Stack using Queues179
541Excel Sheet Column Title Leetcode Solution179
542N-th Tribonacci Number Leetcode Solution179
543Convert a normal BST to Balanced BST179
544Isomorphic Strings Leetcode Solution178
545Change the Array into Permutation of Numbers From 1 to N178
546Linked List Cycle II LeetCode Solution178
547Best Time to Buy and Sell Stock178
548Container with Most Water178
549Convert Sorted Array to Binary Search Tree Leetcode Solution177
550First negative integer in every window of size k177
551Assign Cookies Leetcode Solution177
552Minimum Operations to convert X to Y177
553Rearrange a binary string as alternate x and y occurrences177
554Build Array From Permutation Leetcode Solution177
555Implementation of Deque using circular array177
556Check for Balanced Parentheses in an Expression177
557Find Words That Can Be Formed by Characters Leetcode Solution177
558Largest Perimeter Triangle Leetcode Solution177
559Jewels and Stones Leetcode Solution177
560Valid Anagrams177
561Is Subsequence Leetcode Solution177
562Minimum Bracket Reversals177
563Group Multiple Occurrence of Array Elements Ordered by first Occurrence177
564Combinations Leetcode Solution176
565K-th Distinct Element in an Array176
566Shuffle an Array176
567Valid Sudoku176
568Hamming Distance176
569Sum of Left Leaves Leetcode Solutions176
570Arrange given numbers to form the biggest number176
571Distribute Candies to People Leetcode Solution176
572Island Perimeter Leetcode Solution176
573Integer to Roman176
574Gold Mine Problem176
575Remove Linked List Elements Leetcode Solution176
576Rotate List Leetcode Solution175
57701 Matrix LeetCode Solution175
578Summary Ranges Leetcode Solution175
579Unique Binary Search Trees175
580Minimum Delete Operations to make all Elements of Array Same175
581Largest Sum Contiguous Subarray175
582Minimum Knight Moves LeetCode Solution175
583LRU Cache LeetCode Solution174
584Maximum sum rectangle in a 2D matrix174
585Count the number of nodes at given level in a tree using BFS174
586Decode Ways174
587Count all subsequences having product less than K174
588The Knapsack Problem174
589Distance Between Bus Stops Leetcode Solution173
590Shortest Path in a Grid with Obstacles Elimination LeetCode Solution173
591Maximum Number of Chocolates to be Distributed Equally Among k Students173
592Find the smallest positive integer value that cannot be represented as sum of any subset of a given array173
593Insert Interval Leetcode Solution173
5943Sum Closest LeetCode Solution173
595Maximum path sum in a triangle173
596Minimum number of distinct elements after removing m items172
597Trapping Rain Water LeetCode Solution172
598Maximum Distance in Array172
599Minimum number of subsets with distinct elements171
600How to check if two given sets are disjoint?171
601Rotate Image LeetCode Solution171
602Sort Characters By Frequency LeetCode Solution171
603Find minimum difference between any two elements170
604Frog Jump Leetcode Solution170
605K Empty Slots LeetCode170
606Permutation in String Leetcode Solution170
607Word Pattern170
608Same Tree LeetCode Solution170
609Stone Game LeetCode170
610Sieve of Eratosthenes170
611Sort Array By Parity LeetCode Solution170
612Minimum insertions to form a palindrome with permutations allowed169
613Applications of Breadth First Search and Depth First Search169
614Best Time to Buy and Sell Stock LeetCode Solution169
615Painting Fence Algorithm169
616Distance of nearest cell having 1 in a binary matrix169
617Minimum Depth of Binary Tree Leetcode Solution169
618Remove All Occurrences of a Substring LeetCode Solution169
619Replace Elements with Greatest Element on Right Side Leetcode Solution169
620Find if an Expression has Duplicate Parenthesis or Not169
621Printing brackets in Matrix Chain Multiplication Problem169
622Isomorphic Strings169
623Smallest Good Base169
624XOR Operation in an Array Leetcode Solution169
625House Robber168
626Longest Substring with At Most K Distinct Characters LeetCode Solution168
627Minimum Cost to Hire K Workers168
628Reverse a stack without using extra space in O(n)168
629Segregate 0s and 1s in an Array168
630Find Sum of all unique sub-array sum for a given array168
631License Key Formatting Leetcode Solution168
632Tracking current Maximum Element in a Stack168
633Maximum Consecutive Numbers Present in an Array168
634Find the Duplicate Number LeetCode Solution168
635Word Wrap Problem168
636Defanging an IP Address Leetcode Solution168
637Binary Tree Zigzag Level Order Traversal LeetCode Solution167
638Wiggle Sort167
639Iterative Method to find Height of Binary Tree167
640Maximum difference between first and last indexes of an element in array167
641Count Good Nodes in Binary Tree Leetcode Solution167
642Coin Change Problem167
643Sum of All Odd Length Subarrays Leetcode Solution166
644Optimal Account Balancing LeetCode Solution166
645Merge Two Balanced Binary Search Trees166
646Find Maximum Level sum in Binary Tree166
647Best Time to Buy and Sell Stock with Cooldown Leetcode Solution166
648Valid Palindrome II Leetcode Solution166
649Queries for counts of array elements with values in given range166
650Check If It Is a Straight Line Leetcode Solution166
651Minimum Number of Steps to Make Two Strings Anagram Leetcode Solutions166
652How to Create Mergable Stack?166
653Maximum Number of Occurrences of a Substring Leetcode Solution166
654Kth Missing Positive Number Leetcode Solution166
655Non-overlapping sum of two sets166
656GCD Of Two Numbers166
657Valid Palindrome165
658Longest Substring with At Least K Repeating Characters LeetCode Solution165
659Longest Increasing Subsequence165
660Find the Distance Value Between Two Arrays Leetcode Solution165
661Moving Average from Data Stream Leetcode Solution165
662Convert an array to reduced form165
663Flipping an Image LeetCode Solution165
664Path With Maximum Minimum Value LeetCode Solution165
665Strobogrammatic Number LeetCode Solution165
666Employee Free Time LeetCode Solution165
667Find Largest d in Array such that a + b + c = d165
668Delete consecutive same words in a sequence164
669Reorganize String164
670Find pairs with given sum such that elements of pair are in different rows164
671Maximum Number of Coins You Can Get Leetcode Solution164
672Number of Provinces Leetcode Solution164
673Partition Labels LeetCode Solution164
674Letter Combinations of a Phone Number164
675Populating Next Right Pointers in Each Node163
676Recover Binary Search Tree163
677Power of Four Leetcode Solution163
678Edit Distance LeetCode Solution163
679Longest Increasing Path in a Matrix LeetCode Solution163
680Permutation Sequence LeetCode Solution163
681Print the Fibonacci numbers in reverse order163
682Valid Perfect Square Leetcode Solution163
683Number of Dice Rolls With Target Sum LeetCode Solution163
684Reducing Dishes LeetCode Solution163
685Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest163
686Check if a queue can be sorted into another queue using a stack162
687Partition Array Into Three Parts With Equal Sum Leetcode Solution162
688K Empty Slots162
689Form minimum number from given sequence162
690Lucky Numbers in a Matrix Leetcode Solution162
691BFS vs DFS for Binary Tree162
692Sort Array by Increasing Frequency Leetcode Solution162
693Construct BST from given Preorder Traversal162
694Check If Two String Arrays are Equivalent Leetcode Solution162
695To Lower Case Leetcode Solution161
696Reservoir Sampling161
697Inorder Successor of a node in Binary Tree161
698Reversing a Queue using Recursion161
699Binary Tree zigzag level order Traversal161
700Find whether an array is subset of another array161
701Merge Two Binary Trees LeetCode Solution161
702Dynamic Programming Basics161
703Maximum Product of Two Elements in an Array Leetcode Solution161
704Ugly Number Leetcode Solution161
705Remove Invalid Parentheses Leetcode Solution161
706String to Integer (atoi) LeetCode Solution161
707Factorial Trailing Zeroes Leetcode Solution161
708Robot Room Cleaner Leetcode Solution161
709Convert a Number to Hexadecimal Leetcode Solution161
710Subset Sum Leetcode160
711Majority Element II Leetcode Solution160
712Keyboard Row Leetcode Solution160
713Binomial Coefficient160
714Increasing Decreasing String Leetcode Solution160
715Reverse Only Letters LeetCode Solution160
716Delete Nth node from the end of the given linked list160
717Restore IP Addresses Leetcode Solution160
718Find Leaves of Binary Tree LeetCode Solution160
719Unique Paths II Leetcode Solution159
720Add and Search Word – Data structure design LeetCode159
721Decompress Run-Length Encoded List Leetcode Solution159
722Find the largest multiple of 3159
723Bulb Switcher LeetCode Solution159
724Minimum Cost For Tickets Leetcode Solution158
725Find the Smallest Divisor given a Threshold Leetcode Solution158
726Morris Traversal158
727Find the node with minimum value in a Binary Search Tree158
728Find Pair with Greatest Product in Array158
729Perform String Shifts Leetcode158
730Maximum Product of Three Numbers LeetCode Solution158
731Finding K closest element158
732Maximum 69 Number Leetcode Solution158
733First Unique Character in a String LeetCode Solution157
734Sum of f(a[i], a[j]) over all pairs in an array of n integers157
735Find Maximum Depth of Nested Parenthesis in a String157
736Sorted Linked List to Balanced BST157
737Number of Islands II LeetCode Solution157
738Invert Binary Tree LeetCode Solution157
739Minimum Distance Between BST Nodes Leetcode Solution157
740Numbers with prime frequencies greater than or equal to k157
741Merge K Sorted Linked Lists157
742Maximum Depth of N-ary Tree Leetcode Solution156
743Find All Duplicates in an Array LeetCode Solution156
744Non-decreasing Array LeetCode Solution156
745Check If Array Pairs Are Divisible by k LeetCode Solution156
746Tiling Problem156
747Word Pattern LeetCode Solution156
748Hamming Distance Leetcode Solution156
749Queue based approach for first non-repeating character in a stream156
750Generate all possible sorted arrays from alternate elements of two given sorted arrays156
751Find unique character in a string156
752Diagonal Traversal of Binary Tree156
753Largest subarray with equal number of 0s and 1s156
754Special Array With X Elements Greater Than or Equal X Leetcode Solution156
755Bubble sort using two Stacks156
756Student Attendance Record I Leetcode Solution156
757Longest Span with same Sum in two Binary arrays156
758Rank Transform of an Array Leetcode Solution156
759String Compression LeetCode Solution156
760Minimum Height Trees156
761Find Median from Data Stream LeetCode Solution155
762Largest Rectangle in Histogram LeetCode Solution155
763Best Meeting Point LeetCode Solution155
764Largest rectangular sub-matrix whose sum is 0155
765Minimum time required to rot all oranges155
766Search a 2D Matrix II Leetcode Solution155
767Jump Game155
768Find if Path Exists in Graph Leetcode Solution155
769Symmetric Tree Leetcode Solution155
770Kth ancestor of a node in binary tree155
771Maximum Length of a Concatenated String with Unique Characters Leetcode Solution155
772Stack Permutations (Check if an array is stack permutation of other)155
773Binary Tree Maximum Path Sum LeetCode Solution155
774Elements to be added so that all elements of a range are present in array155
775Evaluate Reverse Polish Notation LeetCode Solution155
776Final Prices With a Special Discount in a Shop Leetcode Solution155
777Split a String in Balanced Strings Leetcode Solution154
778Remove Nth Node From End of List Leetcode Solution154
779Maximum Difference Between Increasing Elements LeetCode Solution154
780Minimize Maximum Pair Sum in Array LeetCode Solution154
781k-th missing element in increasing sequence which is not present in a given sequence154
782Remove brackets from an algebraic string containing + and – operators154
783Program for Bridge and Torch problem154
784Snakes and Ladders LeetCode Solution154
785Race Car LeetCode Solution154
786Transpose Graph154
787Count items common to both the lists but with different prices153
788Sort an array according to the order defined by another array153
789N-Queens LeetCode Solution153
790Number of NGEs to the Right153
791Last Stone Weight II LeetCode Solution153
792Minimum Jumps to Reach Home LeetCode Solution153
793Count quadruples from four sorted arrays whose sum is equal to a given value x153
794Valid Number153
795Partition to K Equal Sum Subsets Leetcode Solution153
796Linked List Cycle153
797Deletion in a Binary Tree153
798Search in a Binary Search Tree Leetcode Solution153
799Get Maximum in Generated Array Leetcode Solution152
800Check for Palindrome after every character replacement Query152
801Number Complement Leetcode Solution152
802Minimum swaps to make sequences increasing152
803A Space Optimized DP solution for 0-1 Knapsack Problem152
804Course Schedule II – LeetCode152
805Priority Queue using doubly linked list152
806Remove Duplicates from Sorted List LeetCode Solution152
807Nearest Exit from Entrance in Maze LeetCode Solution152
808Interval Tree152
809Print a Binary Tree in Vertical Order152
810Remove Duplicates from Sorted List II152
811Check if Two Expressions With Brackets are Same152
812Reorder Data in Log Files LeetCode Solution152
813Minimum Time Visiting All Points Leetcode Solution152
814Minimum number of jumps to reach end152
815Spiral Matrix II Leetcode Solution151
816Maximum size subarray sum equals k151
817Find all triplets with zero sum151
818Nested List Weight Sum II LeetCode Solution151
819One Edit Distance LeetCode Solution151
820String comparison containing wildcards151
821Iterative Preorder Traversal151
822Base 7 Leetcode Solution151
823Relative Ranks Leetcode Solution151
824Sort Array By Parity II Leetcode Solution151
825Crawler Log Folder Leetcode Solution151
826Total Numbers With no Repeated Digits in a Range151
827Growable array based stack151
828Subarray Product Less Than K LeetCode Solution151
829Maximum Profit in Job Scheduling Leetcode Solution151
830Form Minimum Number From Given Sequence150
831Convert BST to Min Heap150
832Brick Wall LeetCode Solution150
833Merge Sorted Array LeetCode Solution150
834Maximum Nesting Depth of the Parentheses Leetcode Solution150
835Regular Expression Matching150
836Circular Queue150
837Given an Array of Pairs Find all Symmetric Pairs in it150
838Alien Dictionary LeetCode Solution150
839Check if a given array can represent Preorder Traversal of Binary Search Tree149
840Path with maximum average value149
841Find All Possible Recipes from Given Supplies LeetCode Solution149
842Valid Parentheses Leetcode Solution149
843Subsequence of Size K With the Largest Even Sum LeetCode Solution149
844Longest Subarray Having Count of 1s One More than Count of 0s149
845Make Two Arrays Equal by Reversing Sub-arrays Leetcode Solution149
846Clone Graph LeetCode Solution149
847Sort Colors149
848Insert into a Binary Search Tree Leetcode Solution149
849Can Place Flowers LeetCode Solution149
850Friends Pairing Problem149
851Find the subarray with least average149
852Minimum Number of Taps to Open to Water a Garden LeetCode Solution149
853Check whether a given Binary Tree is Complete or not149
854Partition List Leetcode Solution149
855Top K Frequent Words LeetCode Solution149
856Count Distinct Elements in Every Window of Size K148
857Find the Only Repetitive Element Between 1 to N-1148
858Design a Stack With Increment Operation Leetcode Solution148
859Find Maximum Sum Possible Equal Sum of Three Stacks148
860Binary Search Tree Search and Insertion148
861Guess Number Higher or Lower LeetCode Solution148
862Sequences of given length where every element is more than or equal to twice of previous148
863Level order Traversal in Spiral Form148
864Matrix Chain Multiplication148
865Subset with sum divisible by m148
866Permutation Coefficient148
867Design Browser History LeetCode Solution147
868Repeated Substring Pattern LeetCode Solution147
869Distinct adjacent elements in an array147
870Water Bottles Leetcode Solution147
871Balanced Expression with Replacement147
872Minimum Sum Path in a Triangle147
873Sum of nearest smaller and greater number147
874Tree Traversal (Preorder, Inorder & Postorder)147
875Count Negative Numbers in a Sorted Matrix LeetCode Solution147
876Union and Intersection of two Linked Lists146
877Range LCM Queries146
878Maximum Score After Splitting a String Leetcode Solution146
879GCDs of given index ranges in an array146
880Daily Temperatures Leetcode Solution146
881K’th Largest Element in BST when modification to BST is not allowed146
882Rearrange an Array Such that arr[i] is equal to i146
883Diagonal Traverse LeetCode Solution146
884An Interesting Method to generate Binary Numbers from 1 to n146
885Number of Days Between Two Dates LeetCode Solution146
886Brightest Position on Street LeetCode Solution146
887Identify and Mark Unmatched Parenthesis in an Expression146
888Shortest Word Distance Leetcode Solution146
889LCS (Longest Common Subsequence) of three strings146
890BFS for Disconnected Graph146
891Best Time to Buy and Sell Stock with Transaction Fee Leetcode Solution146
892Sorted Array to Balanced BST146
893Minimum sum of multiplications of n numbers146
894Missing Element in Sorted Array LeetCode Solution146
895Diagonal Traversal LeetCode Solution146
896Three way partitioning of an array around a given range146
897Convert Sorted List to Binary Search Tree145
898Check if an Array is Stack Sortable145
899Delete And Earn145
900Minimum Swaps to Make Strings Equal Leetcode Solution145
901Least Number of Unique Integers after K Removals Leetcode Solution145
902Guess Number Higher or Lower II145
903Find distance between two nodes of a Binary Tree145
904Count ways to reach the nth stair using step 1, 2 or 3145
905Destination City Leetcode Solution145
906Insert Delete GetRandom145
907Check if the given array can represent Level Order Traversal of Binary Search Tree145
908Range sum queries without updates145
909Robot Bounded In Circle LeetCode Solution145
910Check if stack elements are pairwise consecutive145
911Lemonade Change Leetcode Solution145
912Rearrange Array such that arr[i] >= arr[j] if i is even and arr[i] <= arr[j] if i is odd and j < i145
913Merge Two Sorted Lists Leetcode144
914Print Fibonacci sequence using 2 variables144
915Palindrome Partitioning Leetcode Solution144
916Vertical sum in a given binary tree144
917Spiral Matrix III LeetCode Solution144
918Rearrange Spaces Between Words Leetcode Solution144
9194Sum144
920A program to check if a binary tree is BST or not143
921Maximum Frequency Stack Leetcode Solution143
922Alien Dictionary143
923Time Based Key-Value Store LeetCode Solution143
924Split Array Into Consecutive Subsequences143
925Special Positions in a Binary Matrix Leetcode Solution143
926Construct Complete Binary Tree from its Linked List Representation143
927Construct the Rectangle Leetcode Solution143
9283 Sum143
929Lexicographical Numbers Leetcode Solution142
930Iterative Postorder Traversal Using Two Stacks142
931Number of Distinct Islands Leetcode Solution142
932Check if any two intervals overlap among a given set of intervals142
933Queries for GCD of all numbers of an array except elements in a given range142
934Trim a Binary Search Tree142
935Remove Duplicates from Sorted List II LeetCode Solution142
936Set Matrix Zeroes Leetcode Solution142
937Find Common Characters Leetcode Solution142
938Construct BST from its given Level Order Traversal142
939Minimum Height Trees LeetCode Solution142
940Difference Array | Range update query in O(1)142
941Averages of Levels in Binary Tree142
942Longest Palindromic Subsequence142
943Infix to Postfix142
944Binary Tree Longest Consecutive Sequence LeetCode Solution142
945Stone Game II Leetcode142
946Binary array after M range toggle operations141
947Strongly Connected Component141
948Count Subarrays with Same Even and Odd Elements141
949All Unique Triplets that Sum up to a Given Value141
950Find all permuted rows of a given row in a matrix141
951Unique Paths II141
952Analyze User Website Visit Pattern LeetCode Solution141
953Queue using Stacks141
954Largest area rectangular sub-matrix with equal number of 1’s and 0’s141
955Collect maximum points in a grid using two traversals141
956Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space140
957Create Maximum Number140
958Can Make Arithmetic Progression From Sequence Leetcode Solution140
959Pattern Occurrences using Stack140
960Reverse Nodes in K-Group140
961Word Break140
962Count subarrays where second highest lie before highest140
963Find postorder traversal of BST from preorder traversal140
964Intersection of Two Linked Lists LeetCode Solution140
965Merging Intervals140
966Minesweeper LeetCode Solution140
967Three Consecutive Odds Leetcode Solution140
968Sliding Window Maximum140
969Count Submatrices With All Ones LeetCode Solution140
970Number of Equivalent Domino Pairs Leetcode Solution140
971Kth Smallest Element in a BST Leetcode Solution139
972Longest Nice Substring LeetCode Solution139
973Binary Search Tree Delete Operation139
974Length of Longest Fibonacci Subsequence139
975Product of Array Except Self LeetCode Solution139
976Find the Difference Leetcode Solution139
977Maximum Product Subarray139
978Newman-Conway Sequence139
979Dividing Array into Pairs With Sum Divisible by K139
980Count pair with Given Sum139
981Palindrome Partitioning139
982Level Order Traversal of Binary Tree139
983Count Primes in Ranges139
984Height of a generic tree from parent array139
985Maximum Subarray Sum Excluding Certain Elements139
986Median of Two Sorted Arrays138
987Sign of the Product of an Array LeetCode Solution138
988Asteroid Collision LeetCode Solution138
989Maximize Sum of Array after K Negations Leetcode Solution138
990My Calendar I LeetCode Solution138
991K Closest Points to Origin Leetcode Solution138
992Symmetric Tree138
993Check If a Word Occurs As a Prefix of Any Word in a Sentence Leetcode Solution138
994The Maze III LeetCode Solution137
995Maximum Product of Indexes of Next Greater on Left and Right137
996Find Duplicate Subtrees137
997Climbing stairs137
998Largest divisible pairs subset137
999Segment Tree137
1000Valid Boomerang Leetcode Solution137
1001Find the First Circular Tour that visits all the Petrol Pumps137
1002Number Of Longest Increasing Subsequence137
1003Double the first element and move zero to end137
1004Maximum Length of Repeated Subarray137
1005Boundary Traversal of binary tree137
1006Find Maximum of Minimum for Every Window Size in a Given Array137
1007Friends Of Appropriate Ages LeetCode Solution137
1008Make The String Great Leetcode Solution136
1009Compute nCr % p136
1010Construct Binary Tree from given Parent Array representation136
1011Insertion in a Binary Tree136
1012The Painter’s Partition Problem136
1013Maximum weight transformation of a given string136
1014Largest Substring Between Two Equal Characters Leetcode Solution136
1015First missing positive136
1016Maximum subsequence sum such that no three are consecutive136
1017Boolean Parenthesization Problem136
1018String Matching in an Array Leetcode Solution136
1019Morris Inorder Traversal136
1020Largest Number Leetcode Solution136
1021Serialize and Deserialize Binary Tree136
1022Partition Equal Subset Sum136
1023Breadth First Search (BFS) for a Graph136
1024Level order traversal using two Queues136
1025Depth First Search (DFS) for a Graph136
1026Construction of Longest Increasing Subsequence (N log N)136
1027Maximum Number of Ways to Partition an Array LeetCode Solution135
1028Kill Process LeetCode Solution135
1029Next Greater Element III LeetCode Solution135
1030Rearrange an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’135
1031Graph Valid Tree LeetCode Solution135
1032Shortest Completing Word Leetcode Solution135
1033Minimum Index Sum of Two Lists135
1034Decrypt String from Alphabet to Integer Mapping Leetcode Solution135
1035Longest subsequence such that difference between adjacents is one135
1036Binary Search Tree135
1037Rearrange array such that even positioned are greater than odd134
1038Build an Array With Stack Operations Leetcode Solution134
1039Custom Sort String Leetcode Solution134
1040Scramble String LeetCode Solution134
1041Maximum Sum of 3 Non-Overlapping Subarrays134
1042K maximum sums of overlapping contiguous sub-arrays134
1043Design Hit Counter LeetCode Solution134
1044Advantages of BST over Hash Table134
1045Ugly Numbers134
1046Validate Binary Search Tree134
1047Find number of pairs in an array such that their XOR is 0134
1048Number of palindromic paths in a matrix134
1049Balanced Binary Tree133
1050Invalid Transactions LeetCode Solution133
1051Ugly Number II LeetCode Solution133
1052Defanging an IP Address LeetCode Solution133
1053Available Captures for Rook Leetcode Solution133
1054Bitwise AND of Numbers Range LeetCode Solution133
1055Move all negative elements to end in order with extra space allowed132
1056Maximum length subsequence with difference between adjacent elements as either 0 or 1132
1057Iterative Depth First Traversal of Graph132
1058Search in Sorted Rotated Array132
1059Path Sum II LeetCode Solution132
1060Count pairs from two sorted arrays whose sum is equal to a given value x132
1061Count minimum steps to get the given desired array132
1062Employee Importance LeetCode Solution132
1063Add two numbers132
1064Implement Trie (Prefix Tree) Leetcode Solution132
1065Recover Binary Search Tree Leetcode Solution132
1066Lowest Common Ancestor132
1067Super Ugly Number132
1068Binary Tree Right Side View LeetCode Solution131
1069Largest BST Subtree LeetCode Solution131
1070Number of Students Doing Homework at a Given Time Leetcode Solution131
1071Find a Peak Element II LeetCode Solution131
1072Regular Expression Matching Regular Expression Matching LeetCode Solution131
1073Find Peak Element131
1074Generate Parentheses Leetcode Solution131
1075Remove Duplicates from Sorted Array II Leetcode Solution131
1076Maximum difference between frequency of two elements such that element having greater frequency is also greater131
1077Determine Whether Matrix Can Be Obtained By Rotation LeetCode Solution131
1078Subarrays with K Different Integers Leetcode Solution130
1079Smallest Common Region Leetcode Solution130
1080Kth Smallest Element in a Sorted Matrix LeetCode Solution130
1081Day of the Year Leetcode Solution130
1082Populating Next Right Pointers in Each Node Leetcode Solution130
1083Find whether a subarray is in form of a mountain or not130
1084Clone a Binary Tree with Random Pointers130
1085Root to Leaf path with target sum Leetcode Solutions130
1086Number of Closed Islands Leetcode Solution130
1087Rearrange array such that even index elements are smaller and odd index elements are greater130
1088Longest Bitonic Subsequence130
1089Combination Sum IV LeetCode Solution130
1090Increasing Triplet Subsequence LeetCode Solution129
1091Convert BST into a Min-Heap without using array129
1092Find Smallest Range Containing Elements from k Lists129
1093Number of siblings of a given Node in n-ary Tree129
1094Maximize Distance to Closest Person LeetCode Solution129
1095Serialize and Deserialize Binary Tree LeetCode Solution129
1096Minimum Size Subarray Sum129
1097Find the minimum distance between two numbers129
1098Remove Palindromic Subsequences Leetcode Solution129
1099Binary Tree Data Structure129
1100Next Permutation Leetcode Solution129
1101Distinct Subsequences129
1102Types of Binary Tree129
1103Kth Smallest Product of Two Sorted Arrays LeetCode Solution129
1104Consecutive Characters LeetCode Solution129
1105Count Largest Group Leetcode Solution128
1106Find Three Element From Different Three Arrays Such That a + b + c = sum128
1107Constant time range add operation on an array128
1108Path Sum128
1109Construct Binary Tree from Preorder and Postorder Traversal LeetCode Solution128
1110Divisible Pairs Counting128
1111Remove duplicates from sorted array128
1112Find maximum difference between nearest left and right smaller elements128
1113Print all triplets in sorted array that form AP128
1114Level of Each node in a Tree from source node128
1115Iterative method to find ancestors of a given binary tree128
1116Longest Subarray of 1’s After Deleting One Element LeetCode Solution127
1117Maximum Product Subarray127
1118Cutting a Rod127
1119Third Maximum Number Leetcode Solution127
1120Sum of Even Numbers After Queries127
1121Prime Palindrome LeetCode Solution127
1122Mean of Array After Removing Some Elements Leetcode Solution126
1123Cells with Odd Values in a Matrix LeetCode Solution126
1124Bottom View of a Binary Tree126
1125Valid Tic-Tac-Toe State LeetCode Solution126
1126Palindrome Permutation LeetCode Solution126
1127Reformat The String Leetcode Solution126
1128Minimum Absolute Difference in BST Leetcode Solution126
1129Print Right View of a Binary Tree126
1130Products of ranges in an array126
1131Print Next Greater Number of Q queries126
1132Minimum Score Triangulation of Polygon Leetcode Solution126
1133Delete Nodes and Return Forest Leetcode Solution125
1134Search an Element in Sorted Rotated Array125
1135Search Insert Position125
1136Topological Sorting125
1137Write Code to Determine if Two Trees are Identical125
1138Moser-de Bruijn Sequence125
1139Swap Nodes In Pairs124
1140Thousand Separator Leetcode Solution124
1141Subset Sum Problem in O(sum) space124
1142Construct K Palindrome Strings LeetCode Solution124
1143Maximum Binary Tree124
1144Merge two BSTs with limited extra space124
1145Palindromic Substrings Leetcode Solution124
1146Closest Binary Search Tree Value Leetcode Solution124
1147Minimum sum of squares of character counts in a given string after removing k characters123
1148Golomb sequence123
1149Print modified array after executing the commands of addition and subtraction123
1150Check Array Formation Through Concatenation Leetcode Solution123
1151Possible Bipartition LeetCode Solution123
1152Longest Increasing Consecutive Subsequence123
1153Diameter of N-Ary Tree LeetCode Solution123
1154Find Two Non-overlapping Sub-arrays Each With Target Sum LeetCode Solution123
1155Bus Routes Leetcode Solution123
1156Red-Black Tree Introduction122
1157Maximize sum of consecutive differences in a circular array122
1158Kth Smallest Number in Multiplication Table Leetcode Solution122
1159Priority Queue122
1160Maximum Product of Splitted Binary Tree LeetCode Solution122
1161Remove Max Number of Edges to Keep Graph Fully Traversable Leetcode Solution122
1162Queries for Number of Distinct Elements in a Subarray122
1163Find Largest Value in Each Tree Row LeetCode Solution122
1164Minimum Sideway Jumps LeetCode Solution122
1165Find a sorted subsequence of size 3 in linear time122
1166Transform a BST to Greater sum Tree122
1167Search Suggestions System LeetCode Solution122
1168Find maximum length Snake sequence122
1169Decision Tree121
1170Compare Strings by Frequency of the Smallest Character Leetcode Solution121
1171Find the smallest binary digit multiple of given number121
1172Binary Tree to Binary Search Tree Conversion121
1173Count even length binary sequences with same sum of first and second half bits121
1174Longest Repeated Subsequence121
1175Matchsticks to Square Leetcode Solution120
1176Factorial Trailing Zeroes LeetCode Solution120
1177Lowest Common Ancestor in Binary Search Tree120
1178Rotate Array120
1179Swapping Nodes in a Linked List Leetcode Solution120
1180Web Crawler LeetCode Solution120
1181First Bad Version120
1182Convert Sorted Array to Binary Search Tree LeetCode Solutions120
1183Maximum sum bitonic subarray119
1184K’th Largest element in BST using constant extra space119
1185Decrease Elements To Make Array Zigzag LeetCode Solution119
1186Queue Reconstruction by Height119
1187Number of Orders in the Backlog Leetcode Solution119
1188Minimum Cost to Move Chips to The Same Position LeetCode Solution119
1189Reverse a Path in BST using Queue119
1190Valid Triangle Number118
1191Closest Leaf in a Binary Tree LeetCode Solution118
1192Sum of Left Leaves LeetCode Solution118
1193Minimum Moves to Equal Array Elements LeetCode Solution118
1194Reformat Date LeetCode Solution118
1195Given a binary tree, how do you remove all the half nodes?118
1196Graph and its representation118
1197Maximum number of segments of lengths a, b and c118
1198Range Queries for Longest Correct Bracket Subsequence118
1199Moving Stones Until Consecutive Leetcode Solution118
1200Contiguous Array LeetCode Solution118
1201Maximum sum of pairs with specific difference118
1202Count Pairs Whose Products Exist in Array118
1203Guess The Word117
1204Array Queries for multiply replacements and product117
1205How to print maximum number of A’s using given four keys117
1206Kth Smallest Element in a BST117
1207Filter Restaurants by Vegan-Friendly, Price and Distance Leetcode Solution116
1208Lowest Common Ancestor of a Binary Tree Leetcode Solution116
1209Replace two consecutive equal values with one greater116
1210Convert Integer to the Sum of Two No-Zero Integers Leetcode Solution116
1211Champagne Tower LeetCode Solution116
1212Path Crossing Leetcode Solution116
1213Concatenation of Array LeetCode Solution115
1214Perfect Squares LeetCode Solution115
1215Minimum Swaps To Make Sequences Increasing LeetCode Solution115
1216Integer Break LeetCode Solution115
1217Arithmetic Slices II – Subsequence LeetCode Solution115
1218Write a function to get the intersection point of two Linked Lists114
1219Flatten 2D Vector LeetCode Solution114
1220Check Completeness of a Binary Tree LeetCode Solution114
1221Design Skiplist LeetCode Solution114
1222LRU Cache Leetcode Solution114
1223Power of Two114
1224Divide Two Integers Leetcode Solution114
1225The kth Factor of n Leetcode Solution114
1226Maximum Depth Of Binary Tree114
1227Maximum sum of a path in a Right Number Triangle114
1228Range Sum Query using Sparse Table114
1229Merge Sort114
1230Longest Common Prefix Using Word by Word Matching113
1231Check if all levels of two Binary Tree are anagrams or not113
1232Largest Plus Sign Leetcode Solution113
1233BST to a Tree with Sum of all Smaller Keys113
1234Check for Identical BSTs without building the trees113
1235Contiguous Array113
1236Print modified array after multiple array range increment operations113
1237New 21 Game113
1238Maximize Elements Using Another Array113
1239Valid Perfect Square LeetCode Solution113
1240Queries on Probability of Even or Odd Number in given Ranges113
1241Find Minimum in Rotated Sorted Array II LeetCode Solution113
1242Mean of range in array113
1243Sliding Window Median Leetcode Solution112
1244Maximum Value at a Given Index in a Bounded Array LeetCode Solution112
1245Bold Words in String LeetCode Solution112
1246Print Ancestors of a Given Binary Tree Node Without Recursion112
1247Check if each internal node of a BST has exactly one child112
1248Print n terms of Newman-Conway Sequence112
1249Parallel Courses II LeetCode Solution112
1250Symmetric Tree LeetCode Solution Leetcode Solution111
1251Graph Cloning111
1252Maximum Array from Two given Arrays Keeping Order Same111
1253Find minimum number of merge operations to make an array palindrome111
1254Find k-th smallest element in BST (Order Statistics in BST)111
1255Count Subsets Having Distinct Even Numbers111
1256Merge k Sorted Lists Leetcode Solution111
1257Minimum Remove to Make Valid Parentheses LeetCode Solution110
1258Maximum Product Subarray110
1259Missing Number110
1260Count and Toggle Queries on a Binary Array110
1261Smallest Range II Leetcode Solution110
1262Check if two nodes are on the same path in a Tree110
1263Number of elements less than or equal to a given number in a given subarray109
1264Verify Preorder Serialization of a Binary Tree109
1265Image Overlap LeetCode Solution108
1266Next greater element108
1267Excel Sheet Column Title LeetCode Solution108
1268Check If a String Can Break Another String Leetcode Solution108
1269Koko Eating Bananas LeetCode Solution107
1270Orderly Queue LeetCode Solution107
1271Min Cost Climbing Stairs LeetCode Solution107
1272Palindrome Partitioning107
1273Different Ways to Add Parentheses Leetcode Solution106
1274Minimum Time to Collect All Apples in a Tree LeetCode Solution106
1275Check if X can give change to every person in the Queue105
1276Peeking Iterator LeetCode Solution105
1277Longest Substring Without Repeating Characters Leetcode Solution104
1278Newman–Shanks–Williams prime103
1279Merge Sorted Array103
1280Check in binary array the number represented by a subarray is odd or even103
1281Largest Submatrix With Rearrangements LeetCode Solution102
1282Range Minimum Query (Square Root Decomposition and Sparse Table)102
1283Array Nesting Leetcode Solution102
1284Arranging Coins Leetcode Solution101
1285Encoded String With Shortest Length LeetCode Solution100
1286Maximum Sum Increasing Subsequence100
1287Find maximum average subarray of k length100
1288Maximum product of an increasing subsequence99
1289Queries for Decimal Values of Subarrays of a Binary Array99
1290Minimum Total Space Wasted With K Resizing Operations LeetCode Solution99
1291Number of indexes with equal elements in given range99
1292Convert to Base -2 LeetCode Solution98
1293Minimum Number of People to Teach LeetCode Solution98
1294Convert a BST to a Binary Tree such that sum of all greater keys is added to every key97
1295Random Pick Index LeetCode Solution97
1296Binary Tree to Binary Search Tree Conversion using STL set96
1297Add Two Numbers II Leetcode Solution96
1298Vertical Order Traversal of Binary Tree LeetCode Solution96
1299Find the Winner of the Circular Game LeetCode Solution96
1300Continuous Subarray Sum LeetCode Solution96
1301Reach a Number LeetCode Solution96
1302Palindrome Number LeetCode Solution95
1303Queries on XOR of greatest odd divisor of the range95
1304Check given array of size n can represent BST of n levels or not95
1305Minimum Possible Integer After at Most K Adjacent Swaps On Digits LeetCode Solution94
1306Number of Subsequences That Satisfy the Given Sum Condition LeetCode solution94
1307Jump Game IV LeetCode Solution94
1308Insert Delete GetRandom O(1) Leetcode Solution93
1309Design Underground System Leetcode Solution90
1310Print Maximum Length Chain of Pairs89
1311Detect Capital Leetcode Solution87
1312Design A Leaderboard Leetcode Solution86
1313Top K Frequent Elements LeetCode Solution83
1314Minimum Swaps to Group All 1’s Together Leetcode Solution83
1315Substring with Concatenation of All Words Leetcode Solution83
1316Minimum Path Sum Leetcode Solution80
1317Count Sub Islands LeetCode Solution80
1318Binary Tree Inorder Traversal LeetCode Solution80
1319Shifting Letters LeetCode Solution79
1320Longest Common Subsequence LeetCode Solution77
1321Odd Even Linked List Leetcode Solution77
1322Best Meeting Point LeetCode Solution76
1323Find the Town Judge LeetCode Solution76
1324Find the Town Judge LeetCode Solution75
1325Decode String Leetcode Solution75
1326Maximum Population Year LeetCode Solution74
1327Shortest Unsorted Continuous Subarray LeetCode Solution72
1328Sum Root to Leaf Numbers LeetCode Solution71
1329Maximum Population Year LeetCode Solution71
1330Design Add and Search Words Data Structure LeetCode Solution70
1331Rectangle Overlap LeetCode Solution70
1332Flatten Binary Tree to Linked List LeetCode Solution67
1333Stone Game IV LeetCode Solution67
1334Range Sum Query 2D – Immutable LeetCode Solution66
1335Score of Parenthesis LeetCode Solution66
1336Insert into a Sorted Circular Linked List LeetCode Solution66
1337Reveal Cards In Increasing Order Leetcode Solution63
1338Is Graph Bipartite? LeetCode Solution62
1339Valid Triangle Number LeetCode Solution62
1340Divide Chocolate LeetCode Solution53
1341Step-By-Step Directions From a Binary Tree Node to Another LeetCode Solution48
1342Range Sum of BST LeetCode Solution45
1343Reverse Integer Leetcode Solution43
1344Sort Colors LeetCode Solution42
1345Find K Closest Elements LeetCode Solution40
1346Maximum Side Length of a Square with Sum Less than or Equal to Threshold LeetCode Solution38
1347Excel Sheet Column Number LeetCode Solution37
1348Rotate String LeetCode Solution37
1349Maximum Size Subarray Sum Equals k Leetcode Solution19
1350High Five LeetCode Solution18
1351H-Index Leetcode Solution18
1352Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution3
Translate »