Next Greater Element II LeetCode Solution

Difficulty Level Medium
Frequently asked in Adobe Amazon Apple Bloomberg Facebook Google Microsoft Oracle Salesforce VMware Zillow
MindTickle Walmart Global techViews 11

Problem Statement

Next Greater Element II LeetCode Solution – Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

The next greater number of a number x is the first greater number to its traversing order next in the array, which means you could search circularly to find its next greater number. If it doesn’t exist, return -1 for this number.

Example 1:

Input:

 nums = [1,2,1]

Output:

 [2,-1,2]
Explanation: The first 1's next greater number is 2; 
The number 2 can't find next greater number. 
The second 1's next greater number needs to search circularly, which is also 2.

Example 2:

Input:

 nums = [1,2,3,4,3]

Output:

 [2,3,4,-1,4]

Constraints:

  • 1 <= nums.length <= 104
  • -109 <= nums[i] <= 109

Approach

Idea:

  1. first, we find the maxEleIdx in the array
  2. now this problem is the same as the next greater element 1
  3. we traverse from maxEleIdx to 0 then in circular way n-1 to maxEleIdx+1.
  4. to find the next greater element in the array we maintain a monotonically increasing stack
  5. to do this we traverse the nums array from (maxEleIdx to 0  then in circular way n-1 to maxEleIdx+1)
  6. if the stack is not empty, then compare its top element with nums[i],if the nums[i] is greater than the stack’s top element, then we pop from the stack while (!st.empty() && st.top()>=nums[i] )
  7.  now if we find an element in the stack then we store it at ans[idx]
    otherwise, we store -1 at ans[idx]
  8.  now we push nums[i] into the stack as it might be the next greater element for the remaining elements

Code

C++ Program of Next Greater Element II

  1. class Solution {
    public:
        vector<int> nextGreaterElements(vector<int>& nums) {
            int maxEleIdx=0;
            for(int i=1;i<nums.size();i++)
            {
                if(nums[i]>=nums[maxEleIdx])
                {
                    maxEleIdx=i;
                }
            }
            int n=nums.size();
            stack<int> st;  
            vector<int> ans(n);
            int idx=maxEleIdx;   
            for(int i=0;i<nums.size();i++)
            {
                while(!st.empty() && st.top()<=nums[idx])
                    st.pop();
                
                if(st.empty())
                {
                    ans[idx]=-1;
                }
                else
                {
                    ans[idx]=st.top();
                }
                
                st.push(nums[idx]);
                
                idx--;
                
                if(idx<0)
                    idx=nums.size()-1;
            }  
            return ans;
            
        }
    };

    Java Program of Next Greater Element II

class Solution {
    public int[] nextGreaterElements(int[] nums) { 
        int maxEleIdx=0,n=nums.length;
        for(int i=1;i<nums.length;i++)
        {
            if(nums[i]>=nums[maxEleIdx])
            {
                maxEleIdx=i;
            }
        }
        
         int ans[]=new int[nums.length];
        
        int idx=maxEleIdx;
        Stack<Integer> st=new Stack<>();
        
        for(int i=0;i<nums.length;i++)
        {
            while(!st.isEmpty() && st.peek()<=nums[idx])
                st.pop();
            
            if(st.isEmpty())
            {
                ans[idx]=-1;
            }
            else
            {
                ans[idx]=st.peek();
            }
            
            st.push(nums[idx]);
            
            idx--;
            
            if(idx<0)
                idx=nums.length-1;
        }
        return ans;
    }
}

Complexity Analysis for Next Greater Element II LeetCode Solution

Time Complexity

The time complexity of the above code is O(2*n) because we are traversing the array two times.

Space Complexity

The space complexity of the above code is O(n) because we are using the ans array to store the next greater element of every element

 

Top Interview Questions

S.No Interview Question Number of times has been asked
1Delete a node in doubly linked list2831
2Java program to find the number of Nodes in a Binary Tree2508
3Reverse a string without affecting special characters2470
4Delete a node of a linked list at given position1983
5Palindrome using Recursion1884
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 Occurrences1641
9Write a program to print all permutations of a given string1614
10Quick Sort1546
11Find Minimum Distance Between Two Numbers in an Array1479
12Create a Doubly Linked List1454
13Reverse an Array1417
14Smallest window in a string containing all characters of another string1402
15Find a Triplet That Sum to a Given Value1365
16Recursively remove all adjacent duplicates1362
17First Repeating Element1346
18Arrange Even and Odd number such that Odd comes after Even1327
19Sum of numbers in String1324
20Smallest Positive Number Missing in an Unsorted Array1292
21Check if the Elements of an Array are Consecutive1261
22Detect a loop in the Linked List1247
23Largest Sum Contiguous Subarray1235
24Quick Sort on SIngly Linked List1224
25Subarray with Given Sum1217
26Print all Possible Combinations of R Elements in a given Array of size N1209
27Recursive function to do substring search1206
28Find the Maximum Repeating Number in Array1160
29Binary Tree Level order traversal in Java1131
30Find the First and Second Smallest Elements1126
31Check if two linked lists are identical1112
32Maximum Subarray Sum using Divide and Conquer1108
33Remove characters from first string which are in second1077
34Find Leaders in an Array1065
35Swap nodes in the linked list1044
36Find the Number Occurring Odd Number of Times in an Array1009
37Arrange given Numbers to Form the Biggest Number II997
38Find the second most frequent character994
39Given a string find its first non-repeating character976
40Find Triplet in Array With a Given Sum968
41Total number of occurrences of a given item in the linked list960
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 not953
44Print all possible words from phone digits940
45Find the Missing Number931
46Rearrange Positive and Negative Numbers Alternatively in Array926
47Longest Palindromic Substring910
48Segregate even and odd nodes in a linked list893
49Print Longest common subsequence888
50Union and Intersection of Two Linked Lists879
51Transform one string to another using minimum number of given operations873
52Check rearranged string can form a palindrome855
53Rearrange given Array in Maximum Minimum Form851
54Iterative Implementation of Quick Sort841
55Count Possible Triangles826
56Multiplication of Two Matrices808
57Check if the linked list is palindrome801
58Count of Triplets With Sum Less than Given Value801
59Rotate a Linked List801
60Stock Buy Sell to Maximize Profit797
61Insertion Sort770
62Concatenation of two strings768
63Tug of War766
64Count Number of Substrings with K Distinct Character’s762
65Print all duplicates in the input string762
66Find Nearest Greater and Smaller Element751
67The Celebrity Problem744
68Find Pythagorean Triplets from Array743
69Reverse String Without Temporary Variable738
70Remove ‘b’ and ‘ac’ from a given string737
71Find all Common Elements in Given Three Sorted Arrays735
72Remove all duplicates in an unsorted linked list715
73Find the Row with Maximum Number of 1’s712
74Find the Peak Element from an Array704
75Find the subarray whose sum is equal to a given number X702
76Remove Minimum Characters so that Two Strings Become Anagrams697
77Addition of Two Matrices692
78Find Smallest Missing Number in a Sorted Array691
79A Product Array Puzzle689
80Generate all Binary Strings Without Consecutive 1’s683
81Implement Two Stacks in an Array682
82Maximum Sum of Non Consecutive Elements676
83Lexicographic rank of string662
84Maximum Product Subarray II662
85Check if Two given Matrices are Identical653
86Multiplication of Previous and Next653
87Subtraction of Two Matrices642
88Merge K Sorted Arrays and Print Sorted Output639
89Move All the Zeros to the End of the Given Array637
90Divide a string in N equal parts633
91Online Algorithm for Checking Palindrome in a Stream629
92Form Minimum Number from Given Sequence of D’s and I’s628
93Check whether two strings are anagram of each other622
94Remove recurring digits in a given number622
95Sort a linked list that is sorted alternating ascending and descending617
96Maximum Circular Subarray Sum616
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 place610
100Subarray and Subsequence606
101First Circular Tour to Visit all the Petrol Bunks604
102Largest Subarray with Equal Number of 0’s and 1’s602
103Compare two strings(linked lists)600
104Flattening a linked list599
105Maximum Element in an Array which is Increasing and then Decreasing596
106Palindrome Permutations of a String591
107Elements Appear more than N/K times in Array586
108Palindromes in a given range585
109Print all permutations with repetition583
110Majority Element582
111Run length encoding582
112Pangram Checking579
113Minimum insertions to form a shortest palindrome578
114Minimum Characters to be Added at Front to Make String Palindrome572
115Remove all duplicates in a sorted linked list570
116Merge a linked list into another at alternate positions570
117Most repeating character in a string569
118Rearrange a given linked list in-place569
119Minimum number of Merge Operations to make an Array Palindrome567
120Rotate string to get lexicographically minimum string565
121Repeated Subsequence of Length Two or More562
122Print all anagrams together in a sequence of words559
123Reorder an Array According to the Given Indexes557
124Pancake Sorting Problem548
125Two Sum Leetcode Solution544
126Merge Overlapping Intervals II543
127Clone a Linked List with next and random pointer542
1283Sum Leetcode Solution540
129Size of The Subarray With Maximum Sum533
130Transpose of a Matrix533
131Remove Extra Spaces from a String530
132Removing Spaces from a String using stringstream528
133Remove duplicates from a string526
134Check if a given string is a rotation of a palindrome525
135Longest Palindrome can be Formed by Removing or Rearranging Characters524
136Partition Problem524
137Smallest Palindrome after Replacement523
138Maximum Sum Increasing Subsequence523
139Check whether Strings are K Distance Apart or Not514
140Generate all Binary Strings from Given Pattern511
141Length of Longest valid Substring510
142Find Zeros to be Flipped so that Number of Consecutive 1’s is Maximized507
143Insert Node in the Sorted Linked List506
144Delete Last Occurrence504
145Check if Two given Strings are Isomorphic to each other501
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 Array485
150Merge sort better than quick sort for linked lists483
151Number of Smaller Elements on Right Side481
152Find Pair with Given Difference480
153Check length of a String is Equal to the Number Appended at its Last480
154Check if all Rows of a Matrix are Circular Rotations of Each Other479
155Find nth node of the Linked list from the end476
156Longest Common Prefix using Divide and Conquer475
157Print all interleavings of given two strings467
158Find a Fixed Point in a Given Array467
159Sort 0s 1s and 2s in an Array466
160Compare Two Version Numbers465
161Reverse words in a given string462
162Find the Subarray of given length with Least Average461
163Reorder Array Using Given Indexes459
164Print Reverse of a string (Recursion)459
165Merge two sorted linked lists such that merged list is in reverse order459
166Split linked list using alternate nodes458
167Median of Two Sorted Arrays LeetCode Solution456
168Print string of odd length in ‘X’ format445
169Find K Length Subarray of Maximum Average440
170Print all Palindromic Partitions of a String440
171Find Element Using Binary Search in Sorted Array439
172Swap Kth Node from beginning with Kth Node from End438
173Find Duplicates in an Array in Most Efficient Way433
174print all palindromic partitions426
175Flatten a multilevel linked list424
176Shortest Superstring Problem421
177Maximum Length of Chain Pairs420
178Check if String Follows Order of Characters by a Pattern or not419
179Sorting a K Sorted Array415
180Sort a String According to Another String412
181Longest Span with same Sum in two Binary Arrays II404
182Reverse a Linked List in groups402
183Find a Sorted Subsequence of size 3401
184Recursively print all the sentences that can be formed from list of word lists398
185Program to add two binary digits397
186Find the two Numbers with Odd Occurrences in an Unsorted Array394
187Longest Common Prefix Using Binary Search II392
188Reverse a Singly Linked List (Iterative/Non-Recursive)391
189Kth Non-repeating Character388
190Caesar Cipher388
191Rearrange a linked list in Zig-Zag386
192Check if String can Become Empty by Recursively Deleting given Substring384
193Longest Common Prefix Word by Word Matching381
194Rotate Image by 90 degrees380
195Pancake Sorting380
196Permutations of a Given String Using STL373
197Perfect Reversible String372
198Increasing Subsequence of Length three with Maximum Product368
199Merging Two Sorted Arrays368
200Sort a linked list with 0s, 1s and 2s366
201Find the point where a monotonically increasing function becomes positive first time366
2021`s and 2`s complement of binary number366
203Find First non-repeating character in a string365
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 word360
207Delete N nodes after M357
208Longest Common Prefix using Character by Character Matching353
209Count Number of Occurrences in a Sorted Array351
210Palindrome string (number)350
211Split a string347
212Minimum Characters to be Removed to Make a Binary String Alternate343
213Check if a Linked list of Strings form a Palindrome341
214Recursive Implementation of atoi()341
215Print All Distinct Elements of the Array339
216Sorting the array of strings337
217Even Substring Count336
218Maximum occurring character in a string335
219Convert a String that is Repetition of a Substring of Length K334
220Find the first Repeating Number in a Given Array333
221Reverse a singly linked list recursively333
222Valid Parentheses LeetCode Solution333
223Print Shortest Path to Print a String on Screen330
224Can we reverse a linked list in less than O(n) time ?329
225Convert string1 to string2 in one edit327
226Binary Tree to Doubly linked list327
227Reverse a String using Stack326
228wildcard character matching325
229Nth Character in Concatenated Decimal String323
230Sort Elements by Frequency II323
231Maximum Subarray Leetcode Solution322
232Lower Case To Upper Case318
233Count the number of words318
234Merge Two Sorted Arrays316
235Split Four Distinct Strings315
236Find the Lost Element From a Duplicated Array314
237Find middle of the Linked List312
238Longest Common Subsequence with Permutations309
239Count the Pairs at Same Distance as in English Alphabets307
240Matrix Chain Multiplication using Dynamic Programming305
241Next Greater Element in an Array301
242Palindrome Permutation297
243Roman to Integer Leetcode Solution292
244Find Nth Node291
245Searching a node in a Binary Search Tree290
246Find All Pairs With a Given Difference290
247Triplet from three linked lists with given sum286
248Delete a Tree286
249Reverse a String283
250String(represents an integer) to value283
251Word Search Leetcode Solution283
252Print all Possible Ways to Break a String in Bracket Form281
253Reverse Bits281
254Delete a node under given conditions280
255Binary Tree278
256Change Gender of a given String278
257How to Efficiently Implement k Stacks in a Single Array?276
258Sort an array of strings276
259First non Repeating Element274
260Count Pairs With Given Sum274
261Toeplitz Matrix272
262Number of sub-strings which recursively add up to 9272
263Meeting Rooms II LeetCode Solution271
264Longest Common Extension271
265Remove middle points in a linked list of line segments270
266Move all negative elements to one side of array270
267Repeated Substring Pattern269
268N queen problem269
269Remove spaces from a string266
270Longest Palindromic Substring LeetCode Solution266
271Shuffle a given Array264
272Min Stack262
273Number of Islands LeetCode Solution260
274Cuckoo sequence program259
275Dijkstra Algorithm258
276House Robber Leetcode Solution257
277Max stack256
278Find, second, frequent, character256
279Most Frequent Element in an Array254
280Minimize the maximum difference between the heights254
281Fibonacci numbers252
282Clone a linked list with next and random pointer (Hashing)252
283Search Insert Position Leetcode Solution251
284Expression Evaluation250
285Subset Leetcode249
286Sort linked which is sorted on absolute values249
287Valid Palindrome Leetcode Solution248
288Sudoku Solver248
289Plus One Leetcode Solution247
290Evaluation of Postfix Expression246
291Word Search246
292KMP Algorithm246
293Number Of 1 bits246
294Combination Sum Leetcode Solution245
295Reverse words in a string244
296Min Stack Leetcode Solution244
297How to Delete a Linked List244
298Backspace String Compare241
299Set Matrix Zeroes238
300Sqrt(x) Leetcode Solution236
301Merge Sorted Arrays Leetcode Solution236
302Reversing a Queue235
303Rabin Karp Algorithm235
304Pair of Positive Negative Values in an Array234
305Tower Of Hanoi233
306Subarray with 0 sum233
307Common elements in all rows of a given matrix233
308Delete middle element of a stack230
309Product of array except self230
310Contains Duplicate II Leetcode Solution230
311Integer to Roman Leetcode Solution229
312Combination Sum229
313String Compression228
314Intersection of Two Arrays II Leetcode Solution228
315Pascal Triangle Leetcode227
316Reverse individual words226
317Minimum swaps required to bring all elements less than or equal to k together225
318Count subarrays with equal number of 1’s and 0’s225
319Construct Binary Tree from Given Inorder and Preorder Traversals224
320Bellman Ford Algorithm224
321Add Binary Leetcode Solution224
322Count of index pairs with equal elements in an array224
323Implementation of Deque using Doubly Linked List224
324Sliding Window Technique223
325Find Top K (or Most Frequent) Numbers in a Stream223
326Single Number Leetcode Solution223
327Segregate even and odd numbers221
328Minimum Value to Get Positive Step by Step Sum Leetcode Solution221
329Arithmetic Expression Evaluation221
330Contains Duplicate220
331Sort elements by frequency220
332Second Most Repeated Word in a Sequence220
333Palindrome Linked List Leetcode Solution219
334Count Odd Numbers in an Interval Range Leetcode Solution219
335Pow(x, n) Leetcode Solution219
336Page Replacement Algorithms in Operating Systems219
337Group Words With Same Set of Characters218
338Postfix to Infix Conversion218
339Find sum of non-repeating elements (distinct) elements in an array218
340Maximum Number of Balloons Leetcode Solution217
341Kruskal Algorithm217
342Design a stack that supports getMin() in O(1) time and O(1) extra space217
343Next Permutation217
344Smallest Subarray with k Distinct Numbers216
345Third Maximum Number Leetcode Solution215
346Sum of minimum and maximum elements of all subarrays of size k215
347Scramble String215
348Convex Hull Algorithm214
349Permutations Leetcode Solution214
350Longest Substring Without Repeating Characters LeetCode Solution214
351Longest Common Prefix Leetcode Solution213
352Top K Frequent Words213
353Find Lucky Integer in an Array Leetcode Solution213
354Maximum Subarray213
355K-th Smallest Element in a Sorted Matrix213
356Minimum operation to make all elements equal in array212
357Find the Town Judge Leetcode Solution212
358Sorting array using Stacks211
359Find Numbers with Even Number of Digits Leetcode Solution211
360Evaluate Division210
361Majority Element Leetcode Solution210
362Special Number210
363Count subarrays having total distinct elements same as original array210
364First element occurring k times in an array209
365Spiral Matrix LeetCode Solution209
366Given two unsorted arrays find all pairs whose sum is x209
367Number of Good Pairs Leetcode Solution209
368Swap Nodes in Pairs Leetcode Solutions208
369Minimum Path Sum207
370Huffman Coding207
371Prefix to Infix Conversion207
372Merge Two Sorted Lists Leetcode Solutions207
373Count Primes Leetcode Solutions206
374Check if two arrays are equal or not206
375Missing Number Leetcode Solution206
376Pascal’s Triangle II Leetcode Solution206
377Reverse a Number Using Stack206
378Search in Rotated Sorted Array Leetcode Solution205
379Reversing the First K elements of a Queue205
380Minimum Steps to reach target by a Knight205
381Best Time to Buy and Sell Stock  II Leetcode Solution205
382Single Number204
383House Robber II Leetcode Solution204
384Find duplicates in a given array when elements are not limited to a range204
385Maximal Square204
386Group Anagrams204
387Minimum Absolute Difference Leetcode Solution204
388Sort Array by Increasing Frequency Leetcode Solution204
389Power of Two Leetcode Solution203
390Maximum Distance Between two Occurrences of Same Element in Array202
391Convert String To Int202
392Top K Frequent Elements202
393Find All Numbers Disappeared in an Array Leetcode Solution202
394Matrix Diagonal Sum Leetcode Solution202
395Sorting using trivial hash function201
396Expression Contains Redundant Bracket or Not201
397Palindrome Substring Queries201
398Maximum possible difference of two subsets of an array201
399Check if Array Contains Contiguous Integers With Duplicates Allowed201
400Unique Paths Leetcode Solution201
401Fizz Buzz Leetcode201
402Find the first repeating element in an array of integers201
403Running Sum of 1d Array Leetcode Solution201
404How to Implement Stack Using Priority Queue or Heap?200
405Sort Integers by The Number of 1 Bit Leetcode Solution200
406Find Minimum In Rotated Sorted Array200
407Average Salary Excluding the Minimum and Maximum Salary Leetcode Solution200
408Subarray Sum Equals k200
409Zigzag Conversion200
410Unique Paths200
411How Many Numbers Are Smaller Than the Current Number Leetcode Solution199
412Range Sum Query 2D – Immutable Leetcode Solution199
413Cumulative Frequency of Count of Each Element in an Unsorted Array199
414Find the Closest Palindrome number199
415Max Consecutive Ones Leetcode Solution199
416Smallest Element Repeated Exactly K Times199
417Find Number of Employees Under every Employee198
418Coin Change 2 Leetcode Solution198
419Leetcode Permutations198
420Subset sum problem198
421Happy Number Leetcode Solution198
422Find Winner on a Tic Tac Toe Game Leetcode Solution197
423Subarray Sum Equals K LeetCode Solution197
424Decode String197
425Print All Distinct Elements of a Given Integer Array197
426Letter Case Permutation197
427Length of the largest subarray with contiguous elements197
428Difference between highest and least frequencies in an array197
429Reverse Integer196
430Remove Duplicates from Sorted Array Leetcode Solution196
431Monotonic Array LeetCode Solution196
432Best Time to Buy and Sell Stock III Leetcode Solution196
433Sort a stack using recursion196
434Implement Stack and Queue using Deque196
435Fibonacci Number LeetCode Solution195
436LRU Cache Implementation195
437Find top three repeated in array195
438Nth Catalan Number195
439Sum of Subarray Ranges Leetcode Solution194
440Count Substrings with equal number of 0s, 1s and 2s194
441Capacity To Ship Packages Within D Days Leetcode Solution194
442Generate a String With Characters That Have Odd Counts Leetcode Solution194
443Reverse Vowels of a String Leetcode Solution194
444Reverse a Stack Using Recursion194
445Subarrays with distinct elements194
446Find The Duplicate Number193
447Merge Two Sorted Linked Lists193
448Find Median from data Stream193
449Reverse Words in a String III LeetCode Solution193
450Print all subarrays with 0 sum193
451Subtract the Product and Sum of Digits of an Integer Leetcode Solution193
452Maximum Depth of Binary Tree Leetcode Solution193
453Shuffle the Array Leetcode Solution192
454Trapping Rain Water Leetcode Solution192
455Prim’s Algorithm192
456Integer to English words192
457Bipartite Graph192
458Delete a Node from linked list without head pointer192
459Check If N and Its Double Exist Leetcode Solution192
460Target Sum191
461Find the Difference Leetcode Solution191
462Find the Duplicate Element191
463Priority Queue Using Singly Linked List190
464Excel Sheet Column Number Leetcode Solution190
465Longest Common Subsequence190
466Sorting a Queue without Extra Space190
467Find all pairs (a, b) in an array such that a % b = k190
468Kth largest element in an Array Leetcode Solutions190
469Iterative Tower of Hanoi190
470Count and Say190
471Find Common Characters Leetcode Solution190
472Reverse a String190
473Text Justification LeetCode Solution189
474Fizz Buzz189
475Balanced Binary Tree Leetcode Solution189
476Concatenation of Array LeetCode Solution189
477Edit Distance189
478Kids With the Greatest Number of Candies Leetcode Solution188
479Longest Common Prefix using Trie188
480Minimum Moves to Equal Array Elements Leetcode Solution188
481Remove Minimum Number of Elements Such That no Common Element Exist in both Array188
482Reverse a linked list188
483Next Greater Element I Leetcode Solution188
484The K Weakest Rows in a Matrix Leetcode Solution188
485Count pairs from two linked lists whose sum is equal to a given value188
486Degree of an array188
487Number of Steps to Reduce a Number to Zero Leetcode Solution187
488Kth Largest Element in a Stream Leetcode Solution187
489Word Ladder LeetCode Solution187
490Floyd Warshall Algorithm187
491Find elements which are present in first array and not in second187
492Design Parking System Leetcode Solution187
493Find First and Last Position of Element in Sorted Array Leetcode Solution187
494Prefix to Postfix Conversion186
495Merge Overlapping Intervals186
496Find subarray with given sum (Handles Negative Numbers)186
497Shortest Palindrome186
498Slowest Key Leetcode Solution186
499Valid Parenthesis String186
500Top View of Binary Tree186
501Longest subarray not having more than K distinct elements186
502Find four elements that sum to a given value (Hashmap)185
503Zigzag Conversion LeetCode Solution185
504MiniMax Algorithm185
505Count and Say Leetcode Solution185
506The Stock Span Problem185
507Multiply Strings Leetcode Solution185
508Flood Fill LeetCode185
509Find N Unique Integers Sum up to Zero Leetcode Solution185
510Find Index of Closing Bracket for a Given Opening Bracket in an Expression184
511Move Zeroes LeetCode Solution184
512Max Area of Island184
513Jump Game Leetcode Solution184
514Postfix to Prefix Conversion184
515Convert array into Zig-Zag fashion184
516Length of Last Word Leetcode Solution184
517Priority Queue in C++184
518Substring With Concatenation Of All Words184
519Find any one of the multiple repeating elements in read only array183
520Recursion183
521Mobile Numeric Keypad Problem183
522Shuffle String Leetcode Solution183
523Check if a given array contains duplicate elements within k distance from each other183
524Pair with given product183
525Find distinct elements common to all rows of a matrix183
526Peak Index in a Mountain Array183
527Next Greater Frequency Element183
528Intersection of Two Arrays182
529Longest Common Prefix using Sorting182
530Implement a stack using single queue182
531Count number of triplets with product equal to given number182
532Iterative Inorder Traversal of a Binary Tree182
533Excel Sheet Column Title Leetcode Solution181
534Largest Sum Contiguous Subarray181
535Implement Stack using Queues181
536Delete Node in a Linked List Leetcode Solution181
537Last Stone Weight181
538Find missing elements of a range181
539Relative Sort Array Leetcode Solution181
540Contiguous Array Leetcode181
541Koko Eating Bananas Leetcode Solution180
542Smallest Subarray With all Occurrences of a Most Frequent Element180
543Rearrange a binary string as alternate x and y occurrences180
544Change the Array into Permutation of Numbers From 1 to N179
545Is Subsequence Leetcode Solution179
546Distribute Candies to People Leetcode Solution179
547Minimum Bracket Reversals179
548N-th Tribonacci Number Leetcode Solution179
549Valid Sudoku179
550Linked List Cycle II LeetCode Solution179
551Convert a normal BST to Balanced BST179
552Minimum Operations to convert X to Y178
553Best Time to Buy and Sell Stock178
554Container with Most Water178
555Group Multiple Occurrence of Array Elements Ordered by first Occurrence178
556Implementation of Deque using circular array178
557Jewels and Stones Leetcode Solution178
558K-th Distinct Element in an Array178
559Isomorphic Strings Leetcode Solution178
560Arrange given numbers to form the biggest number177
561Check for Balanced Parentheses in an Expression177
562Shuffle an Array177
563First negative integer in every window of size k177
564Gold Mine Problem177
565Assign Cookies Leetcode Solution177
566Sum of Left Leaves Leetcode Solutions177
567Largest Perimeter Triangle Leetcode Solution177
568Unique Binary Search Trees177
569Find Words That Can Be Formed by Characters Leetcode Solution177
570Island Perimeter Leetcode Solution177
571Minimum Knight Moves LeetCode Solution177
572Integer to Roman177
573Convert Sorted Array to Binary Search Tree Leetcode Solution177
574Valid Anagrams177
575Build Array From Permutation Leetcode Solution177
576Combinations Leetcode Solution176
577Trapping Rain Water LeetCode Solution176
578Hamming Distance176
57901 Matrix LeetCode Solution176
580Minimum Delete Operations to make all Elements of Array Same176
581Remove Linked List Elements Leetcode Solution176
582LRU Cache LeetCode Solution175
583Summary Ranges Leetcode Solution175
584Rotate List Leetcode Solution175
585Count all subsequences having product less than K175
586Find the smallest positive integer value that cannot be represented as sum of any subset of a given array175
587The Knapsack Problem175
588Decode Ways174
589Count the number of nodes at given level in a tree using BFS174
5903Sum Closest LeetCode Solution174
591Maximum sum rectangle in a 2D matrix174
592Shortest Path in a Grid with Obstacles Elimination LeetCode Solution174
593Maximum Distance in Array173
594Maximum path sum in a triangle173
595Insert Interval Leetcode Solution173
596Distance Between Bus Stops Leetcode Solution173
597Maximum Number of Chocolates to be Distributed Equally Among k Students173
598Minimum number of distinct elements after removing m items173
599Find minimum difference between any two elements173
600Same Tree LeetCode Solution172
601Minimum insertions to form a palindrome with permutations allowed172
602Find if an Expression has Duplicate Parenthesis or Not171
603Replace Elements with Greatest Element on Right Side Leetcode Solution171
604Painting Fence Algorithm171
605Bubble sort using two Stacks171
606Sort Characters By Frequency LeetCode Solution171
607Rotate Image LeetCode Solution171
608Applications of Breadth First Search and Depth First Search171
609Permutation in String Leetcode Solution171
610Minimum number of subsets with distinct elements171
611Reverse a stack without using extra space in O(n)171
612Sieve of Eratosthenes171
613Stone Game LeetCode171
614How to check if two given sets are disjoint?171
615Frog Jump Leetcode Solution170
616Minimum Cost to Hire K Workers170
617K Empty Slots LeetCode170
618Sort Array By Parity LeetCode Solution170
619Smallest Good Base170
620Word Pattern170
621Longest Increasing Subsequence170
622Remove All Occurrences of a Substring LeetCode Solution170
623XOR Operation in an Array Leetcode Solution170
624Find the Duplicate Number LeetCode Solution170
625Word Wrap Problem170
626Defanging an IP Address Leetcode Solution169
627Maximum Consecutive Numbers Present in an Array169
628Printing brackets in Matrix Chain Multiplication Problem169
629Best Time to Buy and Sell Stock LeetCode Solution169
630Tracking current Maximum Element in a Stack169
631Distance of nearest cell having 1 in a binary matrix169
632House Robber169
633Minimum Depth of Binary Tree Leetcode Solution169
634Non-overlapping sum of two sets169
635Isomorphic Strings169
636Longest Substring with At Most K Distinct Characters LeetCode Solution168
637License Key Formatting Leetcode Solution168
638Optimal Account Balancing LeetCode Solution168
639Segregate 0s and 1s in an Array168
640Valid Palindrome II Leetcode Solution168
641Coin Change Problem168
642Find Sum of all unique sub-array sum for a given array168
643Wiggle Sort168
644Sum of All Odd Length Subarrays Leetcode Solution167
645Count Good Nodes in Binary Tree Leetcode Solution167
646Kth Missing Positive Number Leetcode Solution167
647Check If It Is a Straight Line Leetcode Solution167
648Queries for counts of array elements with values in given range167
649Iterative Method to find Height of Binary Tree167
650Binary Tree Zigzag Level Order Traversal LeetCode Solution167
651Maximum difference between first and last indexes of an element in array167
652How to Create Mergable Stack?167
653Path With Maximum Minimum Value LeetCode Solution167
654Moving Average from Data Stream Leetcode Solution167
655Find Maximum Level sum in Binary Tree167
656Best Time to Buy and Sell Stock with Cooldown Leetcode Solution166
657Employee Free Time LeetCode Solution166
658Minimum Number of Steps to Make Two Strings Anagram Leetcode Solutions166
659Strobogrammatic Number LeetCode Solution166
660Reorganize String166
661Number of Provinces Leetcode Solution166
662Find the Distance Value Between Two Arrays Leetcode Solution166
663Maximum Number of Occurrences of a Substring Leetcode Solution166
664GCD Of Two Numbers166
665Merge Two Balanced Binary Search Trees166
666Valid Palindrome165
667Reducing Dishes LeetCode Solution165
668Convert an array to reduced form165
669Print the Fibonacci numbers in reverse order165
670Letter Combinations of a Phone Number165
671Find Largest d in Array such that a + b + c = d165
672Flipping an Image LeetCode Solution165
673Longest Substring with At Least K Repeating Characters LeetCode Solution165
674Delete consecutive same words in a sequence165
675K Empty Slots164
676Factorial Trailing Zeroes Leetcode Solution164
677Find pairs with given sum such that elements of pair are in different rows164
678Remove Invalid Parentheses Leetcode Solution164
679Maximum Number of Coins You Can Get Leetcode Solution164
680Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest164
681Check If Two String Arrays are Equivalent Leetcode Solution164
682Partition Labels LeetCode Solution164
683Longest Increasing Path in a Matrix LeetCode Solution163
684BFS vs DFS for Binary Tree163
685Partition Array Into Three Parts With Equal Sum Leetcode Solution163
686Permutation Sequence LeetCode Solution163
687Number of Dice Rolls With Target Sum LeetCode Solution163
688Lucky Numbers in a Matrix Leetcode Solution163
689Inorder Successor of a node in Binary Tree163
690To Lower Case Leetcode Solution163
691Increasing Decreasing String Leetcode Solution163
692Recover Binary Search Tree163
693Valid Perfect Square Leetcode Solution163
694Power of Four Leetcode Solution163
695Populating Next Right Pointers in Each Node163
696Delete Nth node from the end of the given linked list163
697Edit Distance LeetCode Solution163
698String to Integer (atoi) LeetCode Solution162
699Merge Two Binary Trees LeetCode Solution162
700Check if a queue can be sorted into another queue using a stack162
701Unique Paths II Leetcode Solution162
702Form minimum number from given sequence162
703Dynamic Programming Basics162
704Maximum Product of Two Elements in an Array Leetcode Solution162
705Ugly Number Leetcode Solution162
706Sort Array by Increasing Frequency Leetcode Solution162
707Reversing a Queue using Recursion162
708Construct BST from given Preorder Traversal162
709Convert a Number to Hexadecimal Leetcode Solution161
710Robot Room Cleaner Leetcode Solution161
711Reverse Only Letters LeetCode Solution161
712Find whether an array is subset of another array161
713Find the Smallest Divisor given a Threshold Leetcode Solution161
714Reservoir Sampling161
715Find Leaves of Binary Tree LeetCode Solution161
716Subset Sum Leetcode161
717Binary Tree zigzag level order Traversal161
718Restore IP Addresses Leetcode Solution160
719Binomial Coefficient160
720Finding K closest element160
721Majority Element II Leetcode Solution160
722Keyboard Row Leetcode Solution160
723Decompress Run-Length Encoded List Leetcode Solution160
724Add and Search Word – Data structure design LeetCode160
725Perform String Shifts Leetcode160
726Find the node with minimum value in a Binary Search Tree159
727Race Car LeetCode Solution159
728Numbers with prime frequencies greater than or equal to k159
729Check if Two Expressions With Brackets are Same159
730Find the largest multiple of 3159
731Bulb Switcher LeetCode Solution159
732Hamming Distance Leetcode Solution158
733Morris Traversal158
734Rank Transform of an Array Leetcode Solution158
735Find Pair with Greatest Product in Array158
736Minimum Distance Between BST Nodes Leetcode Solution158
737Minimum Cost For Tickets Leetcode Solution158
738Merge K Sorted Linked Lists158
739Maximum Product of Three Numbers LeetCode Solution158
740Number of Islands II LeetCode Solution158
741Minimum time required to rot all oranges158
742Generate all possible sorted arrays from alternate elements of two given sorted arrays158
743Maximum 69 Number Leetcode Solution158
744Sum of f(a[i], a[j]) over all pairs in an array of n integers158
745Minimum Height Trees158
746First Unique Character in a String LeetCode Solution157
747Invert Binary Tree LeetCode Solution157
748Find unique character in a string157
749Sorted Linked List to Balanced BST157
750Tiling Problem157
751Find if Path Exists in Graph Leetcode Solution157
752Maximum Depth of N-ary Tree Leetcode Solution157
753String Compression LeetCode Solution157
754Find Maximum Depth of Nested Parenthesis in a String157
755Student Attendance Record I Leetcode Solution157
756Diagonal Traversal of Binary Tree157
757Longest Span with same Sum in two Binary arrays157
758Word Pattern LeetCode Solution157
759Non-decreasing Array LeetCode Solution157
760Elements to be added so that all elements of a range are present in array156
761Find All Duplicates in an Array LeetCode Solution156
762Queue based approach for first non-repeating character in a stream156
763Binary Tree Maximum Path Sum LeetCode Solution156
764Check If Array Pairs Are Divisible by k LeetCode Solution156
765Remove brackets from an algebraic string containing + and – operators156
766Snakes and Ladders LeetCode Solution156
767Best Meeting Point LeetCode Solution156
768Total Numbers With no Repeated Digits in a Range156
769Minimize Maximum Pair Sum in Array LeetCode Solution156
770Symmetric Tree Leetcode Solution156
771Kth ancestor of a node in binary tree156
772Special Array With X Elements Greater Than or Equal X Leetcode Solution156
773Stack Permutations (Check if an array is stack permutation of other)156
774Remove Nth Node From End of List Leetcode Solution156
775Largest subarray with equal number of 0s and 1s156
776Evaluate Reverse Polish Notation LeetCode Solution155
777Largest Rectangle in Histogram LeetCode Solution155
778Largest rectangular sub-matrix whose sum is 0155
779Linked List Cycle155
780Find Median from Data Stream LeetCode Solution155
781Partition to K Equal Sum Subsets Leetcode Solution155
782Maximum Length of a Concatenated String with Unique Characters Leetcode Solution155
783Jump Game155
784Search a 2D Matrix II Leetcode Solution155
785Final Prices With a Special Discount in a Shop Leetcode Solution155
786Split a String in Balanced Strings Leetcode Solution154
787k-th missing element in increasing sequence which is not present in a given sequence154
788Count items common to both the lists but with different prices154
789Base 7 Leetcode Solution154
790Maximum Difference Between Increasing Elements LeetCode Solution154
791Deletion in a Binary Tree154
792Check for Palindrome after every character replacement Query154
793Transpose Graph154
794Search in a Binary Search Tree Leetcode Solution154
795N-Queens LeetCode Solution154
796Program for Bridge and Torch problem154
797Number of NGEs to the Right154
798Valid Number154
799Sort an array according to the order defined by another array154
800Interval Tree154
801Nearest Exit from Entrance in Maze LeetCode Solution153
802Print a Binary Tree in Vertical Order153
803String comparison containing wildcards153
804Last Stone Weight II LeetCode Solution153
805Count quadruples from four sorted arrays whose sum is equal to a given value x153
806Circular Queue153
807Get Maximum in Generated Array Leetcode Solution153
808Minimum Jumps to Reach Home LeetCode Solution153
809Minimum number of jumps to reach end153
810Minimum Time Visiting All Points Leetcode Solution153
811Growable array based stack153
812One Edit Distance LeetCode Solution153
813A Space Optimized DP solution for 0-1 Knapsack Problem152
814Maximum size subarray sum equals k152
815Number Complement Leetcode Solution152
816Iterative Preorder Traversal152
817Remove Duplicates from Sorted List LeetCode Solution152
818Priority Queue using doubly linked list152
819Find all triplets with zero sum152
820Course Schedule II – LeetCode152
821Reorder Data in Log Files LeetCode Solution152
822Subarray Product Less Than K LeetCode Solution152
823Remove Duplicates from Sorted List II152
824Merge Sorted Array LeetCode Solution152
825Longest Subarray Having Count of 1s One More than Count of 0s152
826Minimum swaps to make sequences increasing152
827Nested List Weight Sum II LeetCode Solution152
828Maximum Profit in Job Scheduling Leetcode Solution152
829Relative Ranks Leetcode Solution152
830Crawler Log Folder Leetcode Solution152
831Sort Array By Parity II Leetcode Solution151
832Form Minimum Number From Given Sequence151
833Spiral Matrix II Leetcode Solution151
834Make Two Arrays Equal by Reversing Sub-arrays Leetcode Solution150
835Check if a given array can represent Preorder Traversal of Binary Search Tree150
836Top K Frequent Words LeetCode Solution150
837Given an Array of Pairs Find all Symmetric Pairs in it150
838Maximum Nesting Depth of the Parentheses Leetcode Solution150
839Brick Wall LeetCode Solution150
840Alien Dictionary LeetCode Solution150
841Minimum Number of Taps to Open to Water a Garden LeetCode Solution150
842Path with maximum average value150
843Subset with sum divisible by m150
844Find the subarray with least average150
845Insert into a Binary Search Tree Leetcode Solution150
846Valid Parentheses Leetcode Solution150
847Sum of nearest smaller and greater number150
848Regular Expression Matching150
849Convert BST to Min Heap150
850Can Place Flowers LeetCode Solution150
851Balanced Expression with Replacement149
852Brightest Position on Street LeetCode Solution149
853Clone Graph LeetCode Solution149
854Minimum Sum Path in a Triangle149
855Matrix Chain Multiplication149
856Check whether a given Binary Tree is Complete or not149
857Permutation Coefficient149
858Binary Search Tree Search and Insertion149
859Guess Number Higher or Lower LeetCode Solution149
860Design a Stack With Increment Operation Leetcode Solution149
861Sort Colors149
862Subsequence of Size K With the Largest Even Sum LeetCode Solution149
863Count Distinct Elements in Every Window of Size K149
864Count Negative Numbers in a Sorted Matrix LeetCode Solution149
865Find Maximum Sum Possible Equal Sum of Three Stacks149
866Partition List Leetcode Solution149
867Level order Traversal in Spiral Form149
868Friends Pairing Problem149
869Find All Possible Recipes from Given Supplies LeetCode Solution149
870Tree Traversal (Preorder, Inorder & Postorder)149
871An Interesting Method to generate Binary Numbers from 1 to n148
872Find the Only Repetitive Element Between 1 to N-1148
873Identify and Mark Unmatched Parenthesis in an Expression148
874Range LCM Queries148
875Diagonal Traverse LeetCode Solution148
876Best Time to Buy and Sell Stock with Transaction Fee Leetcode Solution148
877LCS (Longest Common Subsequence) of three strings148
878Sequences of given length where every element is more than or equal to twice of previous148
879Missing Element in Sorted Array LeetCode Solution148
880Sorted Array to Balanced BST148
881Check if stack elements are pairwise consecutive148
882Time Based Key-Value Store LeetCode Solution147
883Design Browser History LeetCode Solution147
884Destination City Leetcode Solution147
885Repeated Substring Pattern LeetCode Solution147
886Distinct adjacent elements in an array147
887Water Bottles Leetcode Solution147
888K’th Largest Element in BST when modification to BST is not allowed147
889Number of Days Between Two Dates LeetCode Solution147
890Convert Sorted List to Binary Search Tree147
891Minimum Swaps to Make Strings Equal Leetcode Solution147
892Insert Delete GetRandom147
893Union and Intersection of two Linked Lists147
894Diagonal Traversal LeetCode Solution147
895Three way partitioning of an array around a given range147
896GCDs of given index ranges in an array146
897Maximum Score After Splitting a String Leetcode Solution146
898Rearrange an Array Such that arr[i] is equal to i146
899Count ways to reach the nth stair using step 1, 2 or 3146
900Daily Temperatures Leetcode Solution146
901Guess Number Higher or Lower II146
902Special Positions in a Binary Matrix Leetcode Solution146
903Shortest Word Distance Leetcode Solution146
904Robot Bounded In Circle LeetCode Solution146
905Minimum sum of multiplications of n numbers146
906BFS for Disconnected Graph146
907Check if an Array is Stack Sortable146
908Spiral Matrix III LeetCode Solution146
909Delete And Earn146
910Queue using Stacks145
911Find distance between two nodes of a Binary Tree145
912Least Number of Unique Integers after K Removals Leetcode Solution145
913Range sum queries without updates145
914Lemonade Change Leetcode Solution145
915Number of Distinct Islands Leetcode Solution145
916Construct Complete Binary Tree from its Linked List Representation145
917Check if the given array can represent Level Order Traversal of Binary Search Tree145
918Rearrange Array such that arr[i] >= arr[j] if i is even and arr[i] <= arr[j] if i is odd and j < i145
919Find Common Characters Leetcode Solution145
920Rearrange Spaces Between Words Leetcode Solution144
921Find all permuted rows of a given row in a matrix144
9224Sum144
923Vertical sum in a given binary tree144
924Set Matrix Zeroes Leetcode Solution144
925Merge Two Sorted Lists Leetcode144
926Construct BST from its given Level Order Traversal144
927Alien Dictionary144
928Palindrome Partitioning Leetcode Solution144
929Print Fibonacci sequence using 2 variables144
930Difference Array | Range update query in O(1)143
931Stone Game II Leetcode143
932Construct the Rectangle Leetcode Solution143
933Check if any two intervals overlap among a given set of intervals143
934Maximum Subarray Sum Excluding Certain Elements143
935Queries for GCD of all numbers of an array except elements in a given range143
936Iterative Postorder Traversal Using Two Stacks143
937Split Array Into Consecutive Subsequences143
938Create Maximum Number143
939Averages of Levels in Binary Tree143
9403 Sum143
941Minimum Height Trees LeetCode Solution143
942Lexicographical Numbers Leetcode Solution143
943Binary Tree Longest Consecutive Sequence LeetCode Solution143
944A program to check if a binary tree is BST or not143
945Maximum Frequency Stack Leetcode Solution143
946Number of Equivalent Domino Pairs Leetcode Solution142
947Count Subarrays with Same Even and Odd Elements142
948Infix to Postfix142
949Strongly Connected Component142
950Trim a Binary Search Tree142
951Analyze User Website Visit Pattern LeetCode Solution142
952Remove Duplicates from Sorted List II LeetCode Solution142
953Largest area rectangular sub-matrix with equal number of 1’s and 0’s142
954Longest Palindromic Subsequence142
955My Calendar I LeetCode Solution141
956Merging Intervals141
957Dividing Array into Pairs With Sum Divisible by K141
958Can Make Arithmetic Progression From Sequence Leetcode Solution141
959All Unique Triplets that Sum up to a Given Value141
960Sliding Window Maximum141
961Unique Paths II141
962Count Submatrices With All Ones LeetCode Solution141
963Collect maximum points in a grid using two traversals141
964Binary array after M range toggle operations141
965Median of Two Sorted Arrays141
966Find postorder traversal of BST from preorder traversal141
967Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space141
968Three Consecutive Odds Leetcode Solution140
969Intersection of Two Linked Lists LeetCode Solution140
970Count pair with Given Sum140
971Maximum Product Subarray140
972Sign of the Product of an Array LeetCode Solution140
973Height of a generic tree from parent array140
974Kth Smallest Element in a BST Leetcode Solution140
975Minesweeper LeetCode Solution140
976Pattern Occurrences using Stack140
977Word Break140
978Count subarrays where second highest lie before highest140
979Maximize Sum of Array after K Negations Leetcode Solution140
980Reverse Nodes in K-Group140
981K Closest Points to Origin Leetcode Solution140
982The Painter’s Partition Problem140
983Count Primes in Ranges140
984Length of Longest Fibonacci Subsequence139
985Product of Array Except Self LeetCode Solution139
986Palindrome Partitioning139
987Longest Nice Substring LeetCode Solution139
988Level Order Traversal of Binary Tree139
989Symmetric Tree139
990Friends Of Appropriate Ages LeetCode Solution139
991Binary Search Tree Delete Operation139
992Newman-Conway Sequence139
993Climbing stairs139
994Find the Difference Leetcode Solution139
995Find Maximum of Minimum for Every Window Size in a Given Array139
996Segment Tree138
997Asteroid Collision LeetCode Solution138
998Check If a Word Occurs As a Prefix of Any Word in a Sentence Leetcode Solution138
999Minimum Index Sum of Two Lists138
1000Largest Substring Between Two Equal Characters Leetcode Solution138
1001Largest divisible pairs subset138
1002Find number of pairs in an array such that their XOR is 0138
1003Largest Number Leetcode Solution138
1004Valid Boomerang Leetcode Solution138
1005Number Of Longest Increasing Subsequence138
1006Maximum Product of Indexes of Next Greater on Left and Right137
1007Depth First Search (DFS) for a Graph137
1008Number of palindromic paths in a matrix137
1009Boolean Parenthesization Problem137
1010Find Duplicate Subtrees137
1011Shortest Completing Word Leetcode Solution137
1012Breadth First Search (BFS) for a Graph137
1013Maximum subsequence sum such that no three are consecutive137
1014String Matching in an Array Leetcode Solution137
1015Compute nCr % p137
1016Insertion in a Binary Tree137
1017Construct Binary Tree from given Parent Array representation137
1018The Maze III LeetCode Solution137
1019Maximum Length of Repeated Subarray137
1020Boundary Traversal of binary tree137
1021Graph Valid Tree LeetCode Solution137
1022Double the first element and move zero to end137
1023Merge Sort137
1024Construction of Longest Increasing Subsequence (N log N)137
1025Find the First Circular Tour that visits all the Petrol Pumps137
1026Kill Process LeetCode Solution136
1027Maximum Number of Ways to Partition an Array LeetCode Solution136
1028Decrypt String from Alphabet to Integer Mapping Leetcode Solution136
1029Scramble String LeetCode Solution136
1030Partition Equal Subset Sum136
1031Next Greater Element III LeetCode Solution136
1032Serialize and Deserialize Binary Tree136
1033Morris Inorder Traversal136
1034Make The String Great Leetcode Solution136
1035Binary Search Tree136
1036Maximum weight transformation of a given string136
1037Rearrange an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’136
1038Level order traversal using two Queues136
1039First missing positive136
1040Count minimum steps to get the given desired array136
1041K maximum sums of overlapping contiguous sub-arrays135
1042Design Hit Counter LeetCode Solution135
1043Iterative Depth First Traversal of Graph135
1044Longest subsequence such that difference between adjacents is one135
1045Add two numbers135
1046Build an Array With Stack Operations Leetcode Solution135
1047Advantages of BST over Hash Table135
1048Maximum Sum of 3 Non-Overlapping Subarrays135
1049Invalid Transactions LeetCode Solution135
1050Maximum difference between frequency of two elements such that element having greater frequency is also greater134
1051Employee Importance LeetCode Solution134
1052Rearrange array such that even positioned are greater than odd134
1053Balanced Binary Tree134
1054Ugly Numbers134
1055Validate Binary Search Tree134
1056Available Captures for Rook Leetcode Solution134
1057Custom Sort String Leetcode Solution134
1058Path Sum II LeetCode Solution134
1059Implement Trie (Prefix Tree) Leetcode Solution133
1060Ugly Number II LeetCode Solution133
1061Count pairs from two sorted arrays whose sum is equal to a given value x133
1062Kth Smallest Element in a Sorted Matrix LeetCode Solution133
1063Bitwise AND of Numbers Range LeetCode Solution133
1064Super Ugly Number133
1065Maximum length subsequence with difference between adjacent elements as either 0 or 1133
1066Recover Binary Search Tree Leetcode Solution133
1067Generate Parentheses Leetcode Solution133
1068Defanging an IP Address LeetCode Solution133
1069Regular Expression Matching Regular Expression Matching LeetCode Solution132
1070Largest BST Subtree LeetCode Solution132
1071Move all negative elements to end in order with extra space allowed132
1072Lowest Common Ancestor132
1073Find Peak Element132
1074Root to Leaf path with target sum Leetcode Solutions132
1075Remove Duplicates from Sorted Array II Leetcode Solution132
1076Populating Next Right Pointers in Each Node Leetcode Solution132
1077Search in Sorted Rotated Array132
1078Subarrays with K Different Integers Leetcode Solution131
1079Find a Peak Element II LeetCode Solution131
1080Longest Bitonic Subsequence131
1081Remove Palindromic Subsequences Leetcode Solution131
1082Number of Closed Islands Leetcode Solution131
1083Determine Whether Matrix Can Be Obtained By Rotation LeetCode Solution131
1084Number of Students Doing Homework at a Given Time Leetcode Solution131
1085Rearrange array such that even index elements are smaller and odd index elements are greater131
1086Minimum Size Subarray Sum131
1087Binary Tree Right Side View LeetCode Solution131
1088Day of the Year Leetcode Solution130
1089Minimum Absolute Difference in BST Leetcode Solution130
1090Kth Smallest Product of Two Sorted Arrays LeetCode Solution130
1091Find whether a subarray is in form of a mountain or not130
1092Number of siblings of a given Node in n-ary Tree130
1093Types of Binary Tree130
1094Clone a Binary Tree with Random Pointers130
1095Find Smallest Range Containing Elements from k Lists130
1096Smallest Common Region Leetcode Solution130
1097Maximize Distance to Closest Person LeetCode Solution130
1098Combination Sum IV LeetCode Solution130
1099Consecutive Characters LeetCode Solution129
1100Serialize and Deserialize Binary Tree LeetCode Solution129
1101Find the minimum distance between two numbers129
1102Find maximum difference between nearest left and right smaller elements129
1103Next Permutation Leetcode Solution129
1104Count Largest Group Leetcode Solution129
1105Increasing Triplet Subsequence LeetCode Solution129
1106Level of Each node in a Tree from source node129
1107Distinct Subsequences129
1108Construct K Palindrome Strings LeetCode Solution129
1109Binary Tree Data Structure129
1110Palindrome Permutation LeetCode Solution129
1111Path Sum129
1112Convert BST into a Min-Heap without using array129
1113Constant time range add operation on an array128
1114Print all triplets in sorted array that form AP128
1115Remove duplicates from sorted array128
1116Valid Tic-Tac-Toe State LeetCode Solution128
1117Construct Binary Tree from Preorder and Postorder Traversal LeetCode Solution128
1118Cutting a Rod128
1119Third Maximum Number Leetcode Solution128
1120Find Three Element From Different Three Arrays Such That a + b + c = sum128
1121Divisible Pairs Counting128
1122Maximum Product Subarray128
1123Iterative method to find ancestors of a given binary tree128
1124Prime Palindrome LeetCode Solution127
1125Sum of Even Numbers After Queries127
1126Print Next Greater Number of Q queries127
1127Products of ranges in an array127
1128Delete Nodes and Return Forest Leetcode Solution127
1129Longest Subarray of 1’s After Deleting One Element LeetCode Solution127
1130Bottom View of a Binary Tree127
1131Reformat The String Leetcode Solution127
1132Mean of Array After Removing Some Elements Leetcode Solution127
1133Print Right View of a Binary Tree126
1134Write Code to Determine if Two Trees are Identical126
1135Minimum Score Triangulation of Polygon Leetcode Solution126
1136Find maximum length Snake sequence126
1137Longest Increasing Consecutive Subsequence126
1138Minimum sum of squares of character counts in a given string after removing k characters126
1139Moser-de Bruijn Sequence126
1140Thousand Separator Leetcode Solution126
1141Cells with Odd Values in a Matrix LeetCode Solution126
1142Search Insert Position126
1143Maximum Product of Splitted Binary Tree LeetCode Solution125
1144Merge two BSTs with limited extra space125
1145Swap Nodes In Pairs125
1146Palindromic Substrings Leetcode Solution125
1147Search an Element in Sorted Rotated Array125
1148Red-Black Tree Introduction125
1149Topological Sorting125
1150Priority Queue124
1151Find Two Non-overlapping Sub-arrays Each With Target Sum LeetCode Solution124
1152Diameter of N-Ary Tree LeetCode Solution124
1153Maximum Binary Tree124
1154Check Array Formation Through Concatenation Leetcode Solution124
1155Subset Sum Problem in O(sum) space124
1156Closest Binary Search Tree Value Leetcode Solution124
1157Bus Routes Leetcode Solution123
1158Queries for Number of Distinct Elements in a Subarray123
1159Possible Bipartition LeetCode Solution123
1160Print modified array after executing the commands of addition and subtraction123
1161Golomb sequence123
1162Minimum Sideway Jumps LeetCode Solution123
1163Transform a BST to Greater sum Tree123
1164Find Largest Value in Each Tree Row LeetCode Solution123
1165Minimum Cost to Move Chips to The Same Position LeetCode Solution122
1166Search Suggestions System LeetCode Solution122
1167Count even length binary sequences with same sum of first and second half bits122
1168Binary Tree to Binary Search Tree Conversion122
1169Kth Smallest Number in Multiplication Table Leetcode Solution122
1170Longest Repeated Subsequence122
1171Maximize sum of consecutive differences in a circular array122
1172Remove Max Number of Edges to Keep Graph Fully Traversable Leetcode Solution122
1173Rotate Array122
1174Find a sorted subsequence of size 3 in linear time122
1175Web Crawler LeetCode Solution122
1176Find the smallest binary digit multiple of given number121
1177Graph and its representation121
1178Swapping Nodes in a Linked List Leetcode Solution121
1179Compare Strings by Frequency of the Smallest Character Leetcode Solution121
1180Matchsticks to Square Leetcode Solution121
1181Decision Tree121
1182Number of Orders in the Backlog Leetcode Solution120
1183Convert Sorted Array to Binary Search Tree LeetCode Solutions120
1184First Bad Version120
1185K’th Largest element in BST using constant extra space120
1186Count Pairs Whose Products Exist in Array120
1187Factorial Trailing Zeroes LeetCode Solution120
1188Decrease Elements To Make Array Zigzag LeetCode Solution120
1189Reformat Date LeetCode Solution120
1190Reverse a Path in BST using Queue120
1191Minimum Moves to Equal Array Elements LeetCode Solution120
1192Contiguous Array LeetCode Solution120
1193Lowest Common Ancestor in Binary Search Tree120
1194Maximum sum bitonic subarray119
1195Given a binary tree, how do you remove all the half nodes?119
1196Sum of Left Leaves LeetCode Solution119
1197Maximum sum of pairs with specific difference119
1198Valid Triangle Number119
1199Queue Reconstruction by Height119
1200How to print maximum number of A’s using given four keys119
1201Lowest Common Ancestor of a Binary Tree Leetcode Solution118
1202Moving Stones Until Consecutive Leetcode Solution118
1203Closest Leaf in a Binary Tree LeetCode Solution118
1204Range Queries for Longest Correct Bracket Subsequence118
1205Maximum number of segments of lengths a, b and c118
1206Champagne Tower LeetCode Solution118
1207BST to a Tree with Sum of all Smaller Keys117
1208Maximum Depth Of Binary Tree117
1209Filter Restaurants by Vegan-Friendly, Price and Distance Leetcode Solution117
1210Path Crossing Leetcode Solution117
1211Kth Smallest Element in a BST117
1212Guess The Word117
1213Minimum Swaps To Make Sequences Increasing LeetCode Solution117
1214Array Queries for multiply replacements and product117
1215Write a function to get the intersection point of two Linked Lists116
1216Replace two consecutive equal values with one greater116
1217Convert Integer to the Sum of Two No-Zero Integers Leetcode Solution116
1218LRU Cache Leetcode Solution116
1219Integer Break LeetCode Solution116
1220Concatenation of Array LeetCode Solution116
1221Flatten 2D Vector LeetCode Solution115
1222Arithmetic Slices II – Subsequence LeetCode Solution115
1223Divide Two Integers Leetcode Solution115
1224Queries on Probability of Even or Odd Number in given Ranges115
1225Power of Two115
1226Perfect Squares LeetCode Solution115
1227Maximum sum of a path in a Right Number Triangle115
1228Check if all levels of two Binary Tree are anagrams or not115
1229Maximum Array from Two given Arrays Keeping Order Same115
1230Maximum Value at a Given Index in a Bounded Array LeetCode Solution115
1231Range Sum Query using Sparse Table115
1232New 21 Game115
1233Valid Perfect Square LeetCode Solution115
1234The kth Factor of n Leetcode Solution114
1235Design Skiplist LeetCode Solution114
1236Check Completeness of a Binary Tree LeetCode Solution114
1237Maximize Elements Using Another Array114
1238Mean of range in array114
1239Sliding Window Median Leetcode Solution114
1240Check if each internal node of a BST has exactly one child114
1241Bold Words in String LeetCode Solution113
1242Longest Common Prefix Using Word by Word Matching113
1243Check for Identical BSTs without building the trees113
1244Largest Plus Sign Leetcode Solution113
1245Contiguous Array113
1246Print modified array after multiple array range increment operations113
1247Find Minimum in Rotated Sorted Array II LeetCode Solution113
1248Find k-th smallest element in BST (Order Statistics in BST)112
1249Count Subsets Having Distinct Even Numbers112
1250Print n terms of Newman-Conway Sequence112
1251Graph Cloning112
1252Find minimum number of merge operations to make an array palindrome112
1253Print Ancestors of a Given Binary Tree Node Without Recursion112
1254Parallel Courses II LeetCode Solution112
1255Missing Number111
1256Symmetric Tree LeetCode Solution Leetcode Solution111
1257Maximum Product Subarray111
1258Merge k Sorted Lists Leetcode Solution111
1259Minimum Remove to Make Valid Parentheses LeetCode Solution110
1260Verify Preorder Serialization of a Binary Tree110
1261Smallest Range II Leetcode Solution110
1262Check if two nodes are on the same path in a Tree110
1263Count and Toggle Queries on a Binary Array110
1264Image Overlap LeetCode Solution110
1265Excel Sheet Column Title LeetCode Solution110
1266Number of elements less than or equal to a given number in a given subarray109
1267Next greater element109
1268Check If a String Can Break Another String Leetcode Solution108
1269Minimum Time to Collect All Apples in a Tree LeetCode Solution108
1270Orderly Queue LeetCode Solution107
1271Palindrome Partitioning107
1272Different Ways to Add Parentheses Leetcode Solution107
1273Min Cost Climbing Stairs LeetCode Solution107
1274Koko Eating Bananas LeetCode Solution107
1275Longest Substring Without Repeating Characters Leetcode Solution105
1276Peeking Iterator LeetCode Solution105
1277Check if X can give change to every person in the Queue105
1278Largest Submatrix With Rearrangements LeetCode Solution105
1279Newman–Shanks–Williams prime105
1280Check in binary array the number represented by a subarray is odd or even104
1281Merge Sorted Array103
1282Range Minimum Query (Square Root Decomposition and Sparse Table)103
1283Array Nesting Leetcode Solution102
1284Queries for Decimal Values of Subarrays of a Binary Array102
1285Encoded String With Shortest Length LeetCode Solution102
1286Arranging Coins Leetcode Solution101
1287Maximum Sum Increasing Subsequence101
1288Find maximum average subarray of k length100
1289Maximum product of an increasing subsequence100
1290Number of indexes with equal elements in given range99
1291Minimum Total Space Wasted With K Resizing Operations LeetCode Solution99
1292Minimum Number of People to Teach LeetCode Solution98
1293Convert to Base -2 LeetCode Solution98
1294Reach a Number LeetCode Solution97
1295Convert a BST to a Binary Tree such that sum of all greater keys is added to every key97
1296Random Pick Index LeetCode Solution97
1297Add Two Numbers II Leetcode Solution97
1298Continuous Subarray Sum LeetCode Solution97
1299Check given array of size n can represent BST of n levels or not96
1300Binary Tree to Binary Search Tree Conversion using STL set96
1301Find the Winner of the Circular Game LeetCode Solution96
1302Vertical Order Traversal of Binary Tree LeetCode Solution96
1303Number of Subsequences That Satisfy the Given Sum Condition LeetCode solution95
1304Queries on XOR of greatest odd divisor of the range95
1305Palindrome Number LeetCode Solution95
1306Jump Game IV LeetCode Solution95
1307Insert Delete GetRandom O(1) Leetcode Solution94
1308Minimum Possible Integer After at Most K Adjacent Swaps On Digits LeetCode Solution94
1309Design Underground System Leetcode Solution90
1310Print Maximum Length Chain of Pairs89
1311Design A Leaderboard Leetcode Solution87
1312Detect Capital Leetcode Solution87
1313Minimum Swaps to Group All 1’s Together Leetcode Solution83
1314Top K Frequent Elements LeetCode Solution83
1315Substring with Concatenation of All Words Leetcode Solution83
1316Shifting Letters LeetCode Solution81
1317Count Sub Islands LeetCode Solution81
1318Binary Tree Inorder Traversal LeetCode Solution81
1319Minimum Path Sum Leetcode Solution80
1320Maximum Population Year LeetCode Solution77
1321Odd Even Linked List Leetcode Solution77
1322Longest Common Subsequence LeetCode Solution77
1323Find the Town Judge LeetCode Solution76
1324Decode String Leetcode Solution76
1325Best Meeting Point LeetCode Solution76
1326Find the Town Judge LeetCode Solution75
1327Sum Root to Leaf Numbers LeetCode Solution74
1328Shortest Unsorted Continuous Subarray LeetCode Solution73
1329Rectangle Overlap LeetCode Solution71
1330Maximum Population Year LeetCode Solution71
1331Design Add and Search Words Data Structure LeetCode Solution70
1332Flatten Binary Tree to Linked List LeetCode Solution69
1333Stone Game IV LeetCode Solution67
1334Score of Parenthesis LeetCode Solution67
1335Insert into a Sorted Circular Linked List LeetCode Solution67
1336Range Sum Query 2D – Immutable LeetCode Solution66
1337Reveal Cards In Increasing Order Leetcode Solution63
1338Valid Triangle Number LeetCode Solution63
1339Is Graph Bipartite? LeetCode Solution62
1340Divide Chocolate LeetCode Solution57
1341Step-By-Step Directions From a Binary Tree Node to Another LeetCode Solution49
1342Range Sum of BST LeetCode Solution46
1343Reverse Integer Leetcode Solution46
1344Sort Colors LeetCode Solution42
1345Find K Closest Elements LeetCode Solution40
1346Rotate String LeetCode Solution38
1347Maximum Side Length of a Square with Sum Less than or Equal to Threshold LeetCode Solution38
1348Excel Sheet Column Number LeetCode Solution37
1349H-Index Leetcode Solution20
1350Maximum Size Subarray Sum Equals k Leetcode Solution20
1351High Five LeetCode Solution19
1352Monotonic Array Leetcode Solution14
1353Camelcase Matching Leetcode Solution12
1354Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution11
1355Unique Binary Search Trees LeetCode Solution11
1356Peak Index in a Mountain Array LeetCode Solution11
1357Valid Triangle Number LeetCode Solution9
1358Group Shifted Strings Leetcode Solution9
1359Swim in Rising Water LeetCode Solution7
1360Isomorphic Strings LeetCode Solution7
Translate »