Best Time to Buy and Sell Stock IV LeetCode Solution

Difficulty Level Hard
Frequently asked in Adobe Amazon Apple Bloomberg Citadel DE Shaw Facebook Goldman Sachs Google Nvidia Oracle UberViews 27

Problem Statement:

Best Time to Buy and Sell Stock IV LeetCode Solution: You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.

Find the maximum profit you can achieve. You may complete at most k transactions.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).


Example 1:


 k = 2, prices = [2,4,1]




 Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:


 k = 2, prices = [3,2,6,5,0,3]




 Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.



We will be solving the problem with the concept of dynamic programming. First, we can generate the recursive solution and then can optimize it using memoization. First, we will check for the base case and then will tell the function when to return. Here the base conditions are:

  1. When we reach the last index of the prices array.
  2. When the number of transactions becomes greater than k.

Coming to the logic part. In any given situation we will be having 2 cases.

  1. If previously we bought a stock for some value, then for the current index i, either we can sell the previously bought stock for this price or we can simply move on to the next index i.e., i+1.
  2. If we haven’t bought any stock previously, then for the current index i, either we can buy this ith stock, costing us prices[i] or we can simply move on i+1th index.

In the end, we will be returning the max value from either of the 2 cases. We will use a buy flag to keep track of whether currently, we need to buy a stock or need to sell a stock. Check out the code for a better understanding.

Best Time to Buy and Sell Stock IV LeetCode SolutionPin


Best Time to Buy and Sell Stock IV C++ Solution:

class Solution {
    int n;
    // dp array
    int dp[1001][2][101];
    int helper(int i,bool buy,int k,int sold,vector<int>& prices){
        // Base cases
            return -100000;
            return 0;
        // check if the value already existed 
            return dp[i][buy][sold];
        // buy=true corresponds we had previously bought a stock and vice versa.
            // either cosider the ith stock or move on to the next one
            return dp[i][buy][sold] = max(prices[i] + helper(i+1,not buy,k,sold+1,prices),helper(i+1,buy,k,sold,prices));
            // either cosider the ith stock or move on to the next one
            return dp[i][buy][sold] = max(-prices[i] + helper(i+1,not buy,k,sold,prices),helper(i+1,buy,k,sold,prices));
    int maxProfit(int k, vector<int>& prices) {
        n = prices.size();        
        return max(0,helper(0,0,k,0,prices));

Best Time to Buy and Sell Stock IV Python Solution:

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        dp = {}
        n = len(prices)
        def helper(i,buy,sold):
            if sold>k:
                return -100000
            if i==n:
                return 0
            if (i,buy,sold) in dp:
                return dp[(i,buy,sold)]
            if buy:
                dp[(i,buy,sold)] = max(prices[i] + helper(i+1,not buy,sold+1),helper(i+1,buy,sold))
                return dp[(i,buy,sold)]
                dp[(i,buy,sold)] = max(-prices[i] + helper(i+1,not buy,sold),helper(i+1,buy,sold));
                return dp[(i,buy,sold)]
        return max(0,helper(0,False,0))

Complexity Analysis of Best Time to Buy and Sell Stock IV LeetCode Solution:

  • Time Complexity: The time complexity of the above code is O(nk).
  • Space Complexity: The space complexity of the above code is O(nk).

Top Interview Questions

S.No Interview Question Number of times has been asked
1Delete a node in doubly linked list2887
2Java program to find the number of Nodes in a Binary Tree2541
3Reverse a string without affecting special characters2524
4Palindrome using Recursion2488
5Delete a node of a linked list at given position2022
6Quick Sort1769
7Insert nodes in a linked list in a sorted way (Ascending Order)1709
8Find elements pair from array whose sum equal to number1688
9Sort Elements by Frequency of Occurrences1672
10Write a program to print all permutations of a given string1655
11Find Minimum Distance Between Two Numbers in an Array1518
12Create a Doubly Linked List1484
13Reverse an Array1464
14Smallest window in a string containing all characters of another string1436
15Recursively remove all adjacent duplicates1405
16Find a Triplet That Sum to a Given Value1391
17First Repeating Element1385
18Sum of numbers in String1362
19Arrange Even and Odd number such that Odd comes after Even1357
20Smallest Positive Number Missing in an Unsorted Array1326
21Check if the Elements of an Array are Consecutive1291
22Detect a loop in the Linked List1272
23Largest Sum Contiguous Subarray1262
24Quick Sort on SIngly Linked List1257
25Print all Possible Combinations of R Elements in a given Array of size N1247
26Subarray with Given Sum1247
27Recursive function to do substring search1245
28Find the Maximum Repeating Number in Array1204
29Find the First and Second Smallest Elements1155
30Binary Tree Level order traversal in Java1155
31Check if two linked lists are identical1141
32Maximum Subarray Sum using Divide and Conquer1141
33Remove characters from first string which are in second1114
34Find Leaders in an Array1092
35Swap nodes in the linked list1085
36Find the second most frequent character1034
37Find the Number Occurring Odd Number of Times in an Array1033
38Arrange given Numbers to Form the Biggest Number II1027
39Given a string find its first non-repeating character1014
40Find Triplet in Array With a Given Sum1002
41Given a sorted array and a number x, find the pair in array whose sum is closest to x994
42Total number of occurrences of a given item in the linked list991
43A Program to check if strings are rotations of each other or not989
44Print all possible words from phone digits972
45Find the Missing Number962
46Rearrange Positive and Negative Numbers Alternatively in Array950
47Longest Palindromic Substring944
48Segregate even and odd nodes in a linked list933
49Print Longest common subsequence924
50Transform one string to another using minimum number of given operations913
51Union and Intersection of Two Linked Lists905
52Check rearranged string can form a palindrome895
53Rearrange given Array in Maximum Minimum Form876
54Iterative Implementation of Quick Sort868
55Insertion Sort858
56Count Possible Triangles856
57Multiplication of Two Matrices840
58Count of Triplets With Sum Less than Given Value829
59Stock Buy Sell to Maximize Profit827
60Check if the linked list is palindrome826
61Rotate a Linked List825
62Concatenation of two strings804
63Tug of War798
64Print all duplicates in the input string796
65Count Number of Substrings with K Distinct Character’s794
66Find Nearest Greater and Smaller Element782
67Reverse String Without Temporary Variable777
68The Celebrity Problem771
69Remove ‘b’ and ‘ac’ from a given string769
70Find Pythagorean Triplets from Array768
71Find all Common Elements in Given Three Sorted Arrays763
72Remove all duplicates in an unsorted linked list740
73Find the Row with Maximum Number of 1’s737
74Find the subarray whose sum is equal to a given number X736
75Remove Minimum Characters so that Two Strings Become Anagrams735
76Find the Peak Element from an Array735
77Addition of Two Matrices729
78Find Smallest Missing Number in a Sorted Array725
79Generate all Binary Strings Without Consecutive 1’s724
80A Product Array Puzzle722
81Maximum Sum of Non Consecutive Elements710
82Implement Two Stacks in an Array706
83Lexicographic rank of string697
84Check if Two given Matrices are Identical689
85Maximum Product Subarray II686
86Multiplication of Previous and Next681
87Subtraction of Two Matrices673
88Merge K Sorted Arrays and Print Sorted Output668
89Divide a string in N equal parts665
90Move All the Zeros to the End of the Given Array665
91Form Minimum Number from Given Sequence of D’s and I’s664
92Online Algorithm for Checking Palindrome in a Stream664
93Remove recurring digits in a given number656
94Check whether two strings are anagram of each other656
95Sort a stack using a temporary stack651
96Maximum Circular Subarray Sum649
97Sort a linked list that is sorted alternating ascending and descending645
98Subarray and Subsequence638
99Find the Minimum Element in a Sorted and Rotated Array636
100First Circular Tour to Visit all the Petrol Bunks632
101Move last element of the Linked List at first place632
102Compare two strings(linked lists)628
1033Sum Leetcode Solution628
104Maximum Element in an Array which is Increasing and then Decreasing626
105Palindrome Permutations of a String626
106Largest Subarray with Equal Number of 0’s and 1’s626
107Flattening a linked list623
108Palindromes in a given range621
109Majority Element618
110Minimum insertions to form a shortest palindrome617
111Pangram Checking616
112Run length encoding615
113Print all permutations with repetition613
114Elements Appear more than N/K times in Array611
115Minimum Characters to be Added at Front to Make String Palindrome608
116Most repeating character in a string605
117Two Sum Leetcode Solution601
118Rotate string to get lexicographically minimum string600
119Repeated Subsequence of Length Two or More598
120Merge a linked list into another at alternate positions596
121Remove all duplicates in a sorted linked list595
122Rearrange a given linked list in-place594
123Minimum number of Merge Operations to make an Array Palindrome593
124Print all anagrams together in a sequence of words591
125Reorder an Array According to the Given Indexes580
126Pancake Sorting Problem578
127Merge Overlapping Intervals II567
128Transpose of a Matrix565
129Smallest Palindrome after Replacement565
130Clone a Linked List with next and random pointer565
131Remove duplicates from a string565
132Longest Palindrome can be Formed by Removing or Rearranging Characters564
133Remove Extra Spaces from a String563
134Removing Spaces from a String using stringstream560
135Maximum Sum Increasing Subsequence559
136Size of The Subarray With Maximum Sum558
137Check if a given string is a rotation of a palindrome558
138Partition Problem551
139Generate all Binary Strings from Given Pattern546
140Check whether Strings are K Distance Apart or Not545
141Length of Longest valid Substring541
142Delete Last Occurrence538
143Check if Two given Strings are Isomorphic to each other537
144Find Zeros to be Flipped so that Number of Consecutive 1’s is Maximized534
145Insert Node in the Sorted Linked List532
146Program to Toggle all Characters in a String526
147Maximum difference between two elements such as larger element comes after smaller525
148Given string is interleaving of two other strings or not525
149Check length of a String is Equal to the Number Appended at its Last515
150Count Minimum Steps to Get the given Array514
151Number of Smaller Elements on Right Side512
152Check if all Rows of a Matrix are Circular Rotations of Each Other507
153Find Pair with Given Difference506
154Longest Common Prefix using Divide and Conquer506
155Merge sort better than quick sort for linked lists505
156Compare Two Version Numbers501
157Find nth node of the Linked list from the end497
158Print all interleavings of given two strings496
159Median of Two Sorted Arrays LeetCode Solution495
160Print Reverse of a string (Recursion)495
161Find a Fixed Point in a Given Array494
162Reorder Array Using Given Indexes493
163Sort 0s 1s and 2s in an Array493
164Reverse words in a given string490
165Merge two sorted linked lists such that merged list is in reverse order484
166Find the Subarray of given length with Least Average484
167Split linked list using alternate nodes483
168Print all Palindromic Partitions of a String475
169Print string of odd length in ‘X’ format471
170Find Element Using Binary Search in Sorted Array468
171Find K Length Subarray of Maximum Average465
172Swap Kth Node from beginning with Kth Node from End461
173Find Duplicates in an Array in Most Efficient Way459
174Shortest Superstring Problem454
175print all palindromic partitions454
176Check if String Follows Order of Characters by a Pattern or not450
177Maximum Length of Chain Pairs448
178Sort a String According to Another String446
179Flatten a multilevel linked list445
180Sorting a K Sorted Array440
181Program to add two binary digits433
182Find a Sorted Subsequence of size 3427
183Recursively print all the sentences that can be formed from list of word lists427
184Reverse a Linked List in groups426
185Longest Span with same Sum in two Binary Arrays II426
186Longest Common Prefix Using Binary Search II425
187Caesar Cipher425
188Find the two Numbers with Odd Occurrences in an Unsorted Array424
189Kth Non-repeating Character421
190Reverse a Singly Linked List (Iterative/Non-Recursive)420
191Check if String can Become Empty by Recursively Deleting given Substring416
192Longest Common Prefix Word by Word Matching411
193Rearrange a linked list in Zig-Zag410
194Rotate Image by 90 degrees406
195Permutations of a Given String Using STL406
196Perfect Reversible String404
197Pancake Sorting403
198Merging Two Sorted Arrays401
199Find First non-repeating character in a string400
2001`s and 2`s complement of binary number398
201Increasing Subsequence of Length three with Maximum Product394
202List items containing all characters of a given word393
203Maximum occurring character in a string393
204Find the point where a monotonically increasing function becomes positive first time392
205Four Elements that Sum to Given390
206Sort a linked list with 0s, 1s and 2s389
207Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes387
208Longest Common Prefix using Character by Character Matching385
209Count Number of Occurrences in a Sorted Array383
210Palindrome string (number)382
211Valid Parentheses LeetCode Solution380
212Delete N nodes after M379
213Minimum Characters to be Removed to Make a Binary String Alternate377
214Even Substring Count375
215Split a string374
216Sorting the array of strings371
217Recursive Implementation of atoi()371
218Convert a String that is Repetition of a Substring of Length K369
219Check if a Linked list of Strings form a Palindrome367
220Print Shortest Path to Print a String on Screen364
221Maximum Subarray Leetcode Solution362
222Print All Distinct Elements of the Array360
223Reverse a String using Stack359
224Convert string1 to string2 in one edit359
225Nth Character in Concatenated Decimal String358
226Find the first Repeating Number in a Given Array358
227Count the number of words358
228Matrix Chain Multiplication using Dynamic Programming358
229wildcard character matching357
230Reverse a singly linked list recursively357
231Lower Case To Upper Case353
232Can we reverse a linked list in less than O(n) time ?351
233Binary Tree to Doubly linked list349
234Sort Elements by Frequency II345
235Find the Lost Element From a Duplicated Array344
236Longest Common Subsequence with Permutations344
237Merge Two Sorted Arrays341
238Split Four Distinct Strings340
239Find middle of the Linked List337
240Count the Pairs at Same Distance as in English Alphabets335
241Roman to Integer Leetcode Solution335
242Toeplitz Matrix329
243Palindrome Permutation327
244Next Greater Element in an Array325
245Word Search Leetcode Solution325
246Move all negative elements to one side of array323
247N queen problem322
248Searching a node in a Binary Search Tree317
249Find All Pairs With a Given Difference317
250Find Nth Node315
251Sudoku Solver315
252Print all Possible Ways to Break a String in Bracket Form314
253First non Repeating Element314
254Reverse Bits314
255Count Pairs With Given Sum313
256String(represents an integer) to value313
257Number of Islands LeetCode Solution313
258Reverse a String312
259Delete a Tree311
260Change Gender of a given String311
261Types of Binary Tree311
262Triplet from three linked lists with given sum311
263Repeated Substring Pattern309
264Meeting Rooms II LeetCode Solution308
265How to Efficiently Implement k Stacks in a Single Array?308
266Fibonacci numbers307
267Reverse a linked list307
268Sort an array of strings307
269Delete a node under given conditions307
270Number of sub-strings which recursively add up to 9305
271Min Stack304
272Most Frequent Element in an Array304
273Longest Palindromic Substring LeetCode Solution304
274Cuckoo sequence program302
275Dijkstra Algorithm302
276Longest Common Extension300
277Binary Tree298
278House Robber Leetcode Solution296
279Remove spaces from a string296
280Max stack295
281Best Time to Buy and Sell Stock  II Leetcode Solution293
282Subset Leetcode292
283Word Search290
284Shuffle a given Array289
285Remove middle points in a linked list of line segments288
286KMP Algorithm288
287Minimize the maximum difference between the heights287
288Find, second, frequent, character287
289Plus One Leetcode Solution287
290Expression Evaluation287
291Combination Sum Leetcode Solution285
292Search Insert Position Leetcode Solution284
293Number Of 1 bits282
294Reverse words in a string282
295Pair of Positive Negative Values in an Array280
296Evaluation of Postfix Expression280
297Set Matrix Zeroes279
298Sliding Window Technique279
299Subarray with 0 sum276
300Min Stack Leetcode Solution276
301Rabin Karp Algorithm276
302Valid Palindrome Leetcode Solution276
303Common elements in all rows of a given matrix273
304Backspace String Compare273
305Sort linked which is sorted on absolute values273
306Merge Sorted Arrays Leetcode Solution272
307Clone a linked list with next and random pointer (Hashing)272
308Sqrt(x) Leetcode Solution269
309Delete middle element of a stack269
310Reversing a Queue268
311Implementation of Deque using Doubly Linked List266
312Contains Duplicate II Leetcode Solution265
313Count of index pairs with equal elements in an array264
314Product of array except self264
315String Compression264
316Contains Duplicate263
317Find Top K (or Most Frequent) Numbers in a Stream263
318Count subarrays with equal number of 1’s and 0’s263
319Intersection of Two Arrays II Leetcode Solution263
320Combination Sum263
321Tower Of Hanoi263
322Reverse individual words262
323Pascal Triangle Leetcode262
324How to Delete a Linked List261
325Count Odd Numbers in an Interval Range Leetcode Solution260
326Page Replacement Algorithms in Operating Systems260
327Minimum swaps required to bring all elements less than or equal to k together260
328Integer to Roman Leetcode Solution259
329Group Words With Same Set of Characters258
330Segregate even and odd numbers258
331Second Most Repeated Word in a Sequence257
332Single Number Leetcode Solution257
333Bellman Ford Algorithm257
334Postfix to Infix Conversion256
335Sum of minimum and maximum elements of all subarrays of size k256
336Find sum of non-repeating elements (distinct) elements in an array256
337Sorting array using Stacks256
338Smallest Subarray with k Distinct Numbers255
339Sort elements by frequency255
340Minimum Value to Get Positive Step by Step Sum Leetcode Solution255
341Add Binary Leetcode Solution255
342Arithmetic Expression Evaluation255
343K-th Smallest Element in a Sorted Matrix254
344Next Permutation253
345Top K Frequent Words253
346Minimum operation to make all elements equal in array252
347Construct Binary Tree from Given Inorder and Preorder Traversals252
348Maximum Number of Balloons Leetcode Solution252
349Pow(x, n) Leetcode Solution251
350Count subarrays having total distinct elements same as original array251
351Palindrome Linked List Leetcode Solution250
352Convex Hull Algorithm250
353Given two unsorted arrays find all pairs whose sum is x250
354First element occurring k times in an array250
355Longest Common Prefix Leetcode Solution249
356Design a stack that supports getMin() in O(1) time and O(1) extra space249
357Scramble String249
358Permutations Leetcode Solution248
359Longest Substring Without Repeating Characters LeetCode Solution248
360Find Lucky Integer in an Array Leetcode Solution248
361Special Number248
362Majority Element Leetcode Solution248
363Kruskal Algorithm247
364Find duplicates in a given array when elements are not limited to a range247
365Evaluate Division246
366Third Maximum Number Leetcode Solution246
367Check if two arrays are equal or not243
368Maximum possible difference of two subsets of an array243
369Reversing the First K elements of a Queue243
370Fizz Buzz Leetcode243
371Spiral Matrix LeetCode Solution243
372Running Sum of 1d Array Leetcode Solution243
373Prefix to Infix Conversion243
374Minimum Path Sum242
375Number of Good Pairs Leetcode Solution242
376Reverse a Number Using Stack242
377Find Numbers with Even Number of Digits Leetcode Solution241
378Huffman Coding241
379Maximum Subarray241
380Maximal Square240
381Find the Town Judge Leetcode Solution240
382Unique Paths240
383Count Primes Leetcode Solutions239
384Range Sum Query 2D – Immutable Leetcode Solution239
385Swap Nodes in Pairs Leetcode Solutions239
386Minimum Steps to reach target by a Knight239
387Group Anagrams239
388Find the Closest Palindrome number238
389Maximum Distance Between two Occurrences of Same Element in Array238
390Single Number238
391Sort Array by Increasing Frequency Leetcode Solution238
392Minimum Absolute Difference Leetcode Solution238
393Zigzag Conversion237
394Find top three repeated in array237
395Find the first repeating element in an array of integers237
396Palindrome Substring Queries236
397Pascal’s Triangle II Leetcode Solution236
398Sorting using trivial hash function236
399Find Number of Employees Under every Employee236
400Cumulative Frequency of Count of Each Element in an Unsorted Array236
401Smallest Element Repeated Exactly K Times236
402Find All Numbers Disappeared in an Array Leetcode Solution235
403Implement Stack and Queue using Deque235
404Power of Two Leetcode Solution235
405Convert String To Int235
406Remove Minimum Number of Elements Such That no Common Element Exist in both Array235
407Check if Array Contains Contiguous Integers With Duplicates Allowed234
408Count Substrings with equal number of 0s, 1s and 2s234
409Sort Integers by The Number of 1 Bit Leetcode Solution234
410Leetcode Permutations234
411How to Implement Stack Using Priority Queue or Heap?233
412Matrix Diagonal Sum Leetcode Solution233
413Letter Case Permutation233
414Missing Number Leetcode Solution233
415Print all subarrays with 0 sum233
416Merge Two Sorted Lists Leetcode Solutions233
417Subarray Sum Equals k233
418Difference between highest and least frequencies in an array233
419Print All Distinct Elements of a Given Integer Array232
420Bipartite Graph232
421Length of the largest subarray with contiguous elements232
422Fizz Buzz232
423Expression Contains Redundant Bracket or Not232
424House Robber II Leetcode Solution232
425Unique Paths Leetcode Solution231
426Subset sum problem231
427Happy Number Leetcode Solution231
428LRU Cache Implementation231
429Top K Frequent Elements231
430Prim’s Algorithm231
431Sort a stack using recursion230
432Search in Rotated Sorted Array Leetcode Solution230
433Find Median from data Stream230
434Count pairs from two linked lists whose sum is equal to a given value230
435Subarrays with distinct elements230
436Decode String230
437Maximum Depth of Binary Tree Leetcode Solution230
438Reverse Integer229
439Average Salary Excluding the Minimum and Maximum Salary Leetcode Solution229
440Find all pairs (a, b) in an array such that a % b = k229
441Find Winner on a Tic Tac Toe Game Leetcode Solution229
442Monotonic Array LeetCode Solution228
443Coin Change 2 Leetcode Solution228
444Reverse a Stack Using Recursion228
445Max Consecutive Ones Leetcode Solution228
446Check If N and Its Double Exist Leetcode Solution228
447Nth Catalan Number227
448Capacity To Ship Packages Within D Days Leetcode Solution227
449Find the Difference Leetcode Solution227
450How Many Numbers Are Smaller Than the Current Number Leetcode Solution226
451Find elements which are present in first array and not in second226
452Pair with given product226
453Find The Duplicate Number226
454Trapping Rain Water Leetcode Solution225
455Subarray Sum Equals K LeetCode Solution225
456Text Justification LeetCode Solution225
457Integer to English words225
458Sum of Subarray Ranges Leetcode Solution225
459Reverse Vowels of a String Leetcode Solution224
460Edit Distance224
461Floyd Warshall Algorithm224
462Best Time to Buy and Sell Stock III Leetcode Solution224
463Count and Say224
464Remove Duplicates from Sorted Array Leetcode Solution224
465Priority Queue Using Singly Linked List224
466Find distinct elements common to all rows of a matrix224
467Fibonacci Number LeetCode Solution224
468Kth largest element in an Array Leetcode Solutions223
469Valid Parenthesis String223
470Find Index of Closing Bracket for a Given Opening Bracket in an Expression223
471Subtract the Product and Sum of Digits of an Integer Leetcode Solution223
472Target Sum223
473Find four elements that sum to a given value (Hashmap)222
474Reverse a String222
475Find Minimum In Rotated Sorted Array222
476The K Weakest Rows in a Matrix Leetcode Solution221
477Longest subarray not having more than K distinct elements221
478Longest Common Prefix using Trie221
479Jump Game Leetcode Solution221
480Design Parking System Leetcode Solution221
481Generate a String With Characters That Have Odd Counts Leetcode Solution221
482Find any one of the multiple repeating elements in read only array221
483Check if a given array contains duplicate elements within k distance from each other220
484Prefix to Postfix Conversion220
485Delete a Node from linked list without head pointer220
486MiniMax Algorithm220
487Word Ladder LeetCode Solution220
488Sorting a Queue without Extra Space220
489Find Common Characters Leetcode Solution220
490Rearrange a binary string as alternate x and y occurrences220
491Shuffle String Leetcode Solution220
492Shuffle the Array Leetcode Solution219
493Flood Fill LeetCode219
494Intersection of Two Arrays219
495Multiply Strings Leetcode Solution218
496Top View of Binary Tree218
497The Stock Span Problem218
498Find missing elements of a range218
499Count number of triplets with product equal to given number218
500Excel Sheet Column Number Leetcode Solution217
501Merge Two Sorted Linked Lists217
502Iterative Tower of Hanoi217
503Degree of an array217
504Best Time to Buy and Sell Stock LeetCode Solution217
505Shortest Palindrome217
506Balanced Binary Tree Leetcode Solution217
507Find subarray with given sum (Handles Negative Numbers)217
508Substring With Concatenation Of All Words217
509Concatenation of Array LeetCode Solution216
510Next Greater Element I Leetcode Solution216
511Slowest Key Leetcode Solution216
512Kids With the Greatest Number of Candies Leetcode Solution216
513Reverse Words in a String III LeetCode Solution216
514Count and Say Leetcode Solution216
515Priority Queue in C++216
516Iterative Inorder Traversal of a Binary Tree216
517Longest Common Subsequence216
518Number of Steps to Reduce a Number to Zero Leetcode Solution216
519Postfix to Prefix Conversion216
520Peak Index in a Mountain Array215
521Implement Stack using Queues215
522K-th Distinct Element in an Array215
523Check for Balanced Parentheses in an Expression215
524Sum of Left Leaves Leetcode Solutions215
525Find the Duplicate Element215
526Max Area of Island215
527Valid Sudoku215
528Move Zeroes LeetCode Solution215
529Longest Common Prefix using Sorting214
530Arrange given numbers to form the biggest number214
532Convert array into Zig-Zag fashion214
533Minimum Knight Moves LeetCode Solution214
534Linked List Cycle II LeetCode Solution214
535Minimum Moves to Equal Array Elements Leetcode Solution214
536Merge Overlapping Intervals213
537Find First and Last Position of Element in Sorted Array Leetcode Solution213
538Container with Most Water213
539Implement a stack using single queue213
540Kth Largest Element in a Stream Leetcode Solution213
541Hamming Distance212
542Jewels and Stones Leetcode Solution212
543Largest Sum Contiguous Subarray212
544Largest Perimeter Triangle Leetcode Solution212
545Find Sum of all unique sub-array sum for a given array212
546Is Subsequence Leetcode Solution212
547Minimum Delete Operations to make all Elements of Array Same212
548Excel Sheet Column Title Leetcode Solution212
549Check if a queue can be sorted into another queue using a stack211
550Next Greater Frequency Element211
551Gold Mine Problem211
552Zigzag Conversion LeetCode Solution211
553Smallest Subarray With all Occurrences of a Most Frequent Element211
554Isomorphic Strings Leetcode Solution211
555Group Multiple Occurrence of Array Elements Ordered by first Occurrence211
556How to check if two given sets are disjoint?210
557Find N Unique Integers Sum up to Zero Leetcode Solution210
558Delete Node in a Linked List Leetcode Solution210
559Last Stone Weight210
560Change the Array into Permutation of Numbers From 1 to N210
561Contiguous Array Leetcode210
562Minimum Bracket Reversals209
563Convert a normal BST to Balanced BST209
564Maximum sum rectangle in a 2D matrix209
565Shuffle an Array209
566N-th Tribonacci Number Leetcode Solution209
567Koko Eating Bananas Leetcode Solution209
568Mobile Numeric Keypad Problem208
569Best Time to Buy and Sell Stock208
570Minimum number of subsets with distinct elements208
5713Sum Closest LeetCode Solution208
572Length of Last Word Leetcode Solution208
573Distribute Candies to People Leetcode Solution208
574Minimum Cost to Hire K Workers208
575Count the number of nodes at given level in a tree using BFS208
576Valid Anagrams208
577Summary Ranges Leetcode Solution208
578Find if an Expression has Duplicate Parenthesis or Not207
579Maximum Distance in Array207
580Implementation of Deque using circular array207
581Find Words That Can Be Formed by Characters Leetcode Solution207
582Number of Provinces Leetcode Solution207
583Decode Ways206
584Maximum path sum in a triangle206
585Shortest Path in a Grid with Obstacles Elimination LeetCode Solution206
586Frog Jump Leetcode Solution206
587Build Array From Permutation Leetcode Solution206
588Trapping Rain Water LeetCode Solution206
589Maximum difference between first and last indexes of an element in array205
590Remove All Occurrences of a Substring LeetCode Solution205
591Smallest Good Base205
592Maximum Number of Occurrences of a Substring Leetcode Solution205
593LRU Cache LeetCode Solution205
594Combinations Leetcode Solution205
59501 Matrix LeetCode Solution205
596Rotate Image LeetCode Solution205
597Longest Increasing Subsequence205
598Relative Sort Array Leetcode Solution205
599First negative integer in every window of size k205
600Integer to Roman205
601Sort Characters By Frequency LeetCode Solution204
602Minimum Operations to convert X to Y204
603Island Perimeter Leetcode Solution204
604Delete consecutive same words in a sequence204
605Iterative Method to find Height of Binary Tree204
606Count all subsequences having product less than K203
607Non-overlapping sum of two sets203
608Word Pattern203
609Sieve of Eratosthenes203
610XOR Operation in an Array Leetcode Solution203
611Remove Linked List Elements Leetcode Solution203
612Assign Cookies Leetcode Solution203
613Minimum number of distinct elements after removing m items203
614Minimum insertions to form a palindrome with permutations allowed202
615Find minimum difference between any two elements202
616Find the smallest positive integer value that cannot be represented as sum of any subset of a given array202
617GCD Of Two Numbers201
618Convert Sorted Array to Binary Search Tree Leetcode Solution201
619The Knapsack Problem201
620Stone Game LeetCode201
621Rotate List Leetcode Solution201
622Bubble sort using two Stacks201
623Insert Interval Leetcode Solution201
624Reverse a stack without using extra space in O(n)201
625Permutation in String Leetcode Solution200
626Defanging an IP Address Leetcode Solution200
627Unique Binary Search Trees200
628Same Tree LeetCode Solution200
629Find Largest d in Array such that a + b + c = d200
630Tracking current Maximum Element in a Stack200
631Maximum Number of Chocolates to be Distributed Equally Among k Students200
632Sum of f(a[i], a[j]) over all pairs in an array of n integers200
633Applications of Breadth First Search and Depth First Search200
634Count Good Nodes in Binary Tree Leetcode Solution199
635Find the Duplicate Number LeetCode Solution199
636Distance Between Bus Stops Leetcode Solution199
637K Empty Slots199
638Longest Increasing Path in a Matrix LeetCode Solution199
639Isomorphic Strings199
640Reorganize String199
641First Unique Character in a String LeetCode Solution198
642Optimal Account Balancing LeetCode Solution198
643How to Create Mergable Stack?198
644Printing brackets in Matrix Chain Multiplication Problem198
645Employee Free Time LeetCode Solution198
646Convert an array to reduced form198
647Form minimum number from given sequence198
648License Key Formatting Leetcode Solution198
649Painting Fence Algorithm197
650Find pairs with given sum such that elements of pair are in different rows197
651Letter Combinations of a Phone Number197
652Minimum Depth of Binary Tree Leetcode Solution197
653Longest Substring with At Most K Distinct Characters LeetCode Solution196
654Reducing Dishes LeetCode Solution196
655Sort Array By Parity LeetCode Solution196
656Word Wrap Problem196
657Replace Elements with Greatest Element on Right Side Leetcode Solution196
658Minimum Number of Steps to Make Two Strings Anagram Leetcode Solutions196
659Convert a Number to Hexadecimal Leetcode Solution196
660Robot Room Cleaner Leetcode Solution195
661Maximum Consecutive Numbers Present in an Array195
662Segregate 0s and 1s in an Array195
663Strobogrammatic Number LeetCode Solution195
664Find Pair with Greatest Product in Array195
665Merge Two Balanced Binary Search Trees195
666House Robber195
667K Empty Slots LeetCode195
668Check If It Is a Straight Line Leetcode Solution195
669Partition Labels LeetCode Solution194
670Coin Change Problem194
671Kth Missing Positive Number Leetcode Solution194
672Queries for counts of array elements with values in given range194
673Largest subarray with equal number of 0s and 1s194
674Moving Average from Data Stream Leetcode Solution194
675Longest Span with same Sum in two Binary arrays194
676Partition Array Into Three Parts With Equal Sum Leetcode Solution193
677Reservoir Sampling193
678Find Maximum Level sum in Binary Tree193
679Longest Substring with At Least K Repeating Characters LeetCode Solution193
680Distance of nearest cell having 1 in a binary matrix193
681Valid Palindrome II Leetcode Solution193
682Maximum Product of Two Elements in an Array Leetcode Solution193
683Find the node with minimum value in a Binary Search Tree193
684Sum of All Odd Length Subarrays Leetcode Solution193
685String to Integer (atoi) LeetCode Solution193
686Check If Two String Arrays are Equivalent Leetcode Solution192
687Flipping an Image LeetCode Solution192
688Best Time to Buy and Sell Stock with Cooldown Leetcode Solution192
689String Compression LeetCode Solution192
690Find the Distance Value Between Two Arrays Leetcode Solution192
691Print the Fibonacci numbers in reverse order192
692Valid Palindrome192
693Power of Four Leetcode Solution192
694Dynamic Programming Basics192
695Find unique character in a string191
696Remove Invalid Parentheses Leetcode Solution191
697Generate all possible sorted arrays from alternate elements of two given sorted arrays191
698Find the Smallest Divisor given a Threshold Leetcode Solution191
699Binary Tree Maximum Path Sum LeetCode Solution191
700Find Leaves of Binary Tree LeetCode Solution191
701Wiggle Sort190
702Number of Dice Rolls With Target Sum LeetCode Solution190
703Delete Nth node from the end of the given linked list190
704Reverse Only Letters LeetCode Solution190
705Increasing Decreasing String Leetcode Solution190
706Unique Paths II Leetcode Solution190
707To Lower Case Leetcode Solution190
708Numbers with prime frequencies greater than or equal to k190
709Inorder Successor of a node in Binary Tree190
710Find the largest multiple of 3190
711Path With Maximum Minimum Value LeetCode Solution190
712Edit Distance LeetCode Solution189
713Non-decreasing Array LeetCode Solution189
714Factorial Trailing Zeroes Leetcode Solution189
715Sort Array by Increasing Frequency Leetcode Solution189
716Lucky Numbers in a Matrix Leetcode Solution189
717Find whether an array is subset of another array189
718Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest189
719Subset Sum Leetcode189
720Maximum Number of Coins You Can Get Leetcode Solution189
721Stack Permutations (Check if an array is stack permutation of other)189
722Reversing a Queue using Recursion188
723Remove brackets from an algebraic string containing + and – operators188
724Bulb Switcher LeetCode Solution188
725Race Car LeetCode Solution188
726Count quadruples from four sorted arrays whose sum is equal to a given value x188
727Find if Path Exists in Graph Leetcode Solution188
728k-th missing element in increasing sequence which is not present in a given sequence188
729Merge Sorted Array LeetCode Solution188
730Recover Binary Search Tree188
731BFS vs DFS for Binary Tree188
732Perform String Shifts Leetcode188
733Populating Next Right Pointers in Each Node188
734Permutation Sequence LeetCode Solution188
735Merge Two Binary Trees LeetCode Solution188
736Snakes and Ladders LeetCode Solution188
737Binary Tree zigzag level order Traversal187
738Keyboard Row Leetcode Solution187
739Minimum Cost For Tickets Leetcode Solution187
740Evaluate Reverse Polish Notation LeetCode Solution187
741Valid Perfect Square Leetcode Solution187
742Maximum Length of a Concatenated String with Unique Characters Leetcode Solution187
743Majority Element II Leetcode Solution187
744Ugly Number Leetcode Solution187
745Tiling Problem187
746Maximum 69 Number Leetcode Solution187
747Binary Tree Zigzag Level Order Traversal LeetCode Solution187
748Find Maximum Depth of Nested Parenthesis in a String187
749Number of NGEs to the Right186
750Split a String in Balanced Strings Leetcode Solution186
751Valid Number186
752Best Meeting Point LeetCode Solution186
753N-Queens LeetCode Solution186
754String comparison containing wildcards186
755Word Pattern LeetCode Solution186
756Rank Transform of an Array Leetcode Solution186
757Print a Binary Tree in Vertical Order186
758Base 7 Leetcode Solution186
759Student Attendance Record I Leetcode Solution186
760Restore IP Addresses Leetcode Solution186
761Growable array based stack185
762Elements to be added so that all elements of a range are present in array185
763Program for Bridge and Torch problem185
764Morris Traversal185
765Maximum Product of Three Numbers LeetCode Solution185
766Minimum sum of multiplications of n numbers185
767Priority Queue using doubly linked list185
768Add and Search Word – Data structure design LeetCode185
769Symmetric Tree Leetcode Solution185
770Construct BST from given Preorder Traversal185
771Find All Possible Recipes from Given Supplies LeetCode Solution185
772Finding K closest element185
773Find Median from Data Stream LeetCode Solution185
774Number of Days Between Two Dates LeetCode Solution185
775Hamming Distance Leetcode Solution185
776Check if Two Expressions With Brackets are Same185
777Maximum Profit in Job Scheduling Leetcode Solution185
778Partition to K Equal Sum Subsets Leetcode Solution184
779Top K Frequent Words LeetCode Solution184
780Binomial Coefficient184
781Regular Expression Matching184
782Brick Wall LeetCode Solution184
783Find All Duplicates in an Array LeetCode Solution184
784Sorted Linked List to Balanced BST184
785Check If Array Pairs Are Divisible by k LeetCode Solution184
786Minimize Maximum Pair Sum in Array LeetCode Solution184
787Check for Palindrome after every character replacement Query184
788Special Array With X Elements Greater Than or Equal X Leetcode Solution184
789Largest Rectangle in Histogram LeetCode Solution183
790Sort an array according to the order defined by another array183
791Search in a Binary Search Tree Leetcode Solution183
792Decompress Run-Length Encoded List Leetcode Solution183
793Jump Game183
794Merge K Sorted Linked Lists183
795Form Minimum Number From Given Sequence183
796Minimum Distance Between BST Nodes Leetcode Solution183
797Minimum Time Visiting All Points Leetcode Solution182
798Minimum Height Trees182
799Maximum Difference Between Increasing Elements LeetCode Solution182
800Nearest Exit from Entrance in Maze LeetCode Solution182
801Maximum Nesting Depth of the Parentheses Leetcode Solution182
802Total Numbers With no Repeated Digits in a Range182
803Kth ancestor of a node in binary tree182
804Queue based approach for first non-repeating character in a stream182
805Largest rectangular sub-matrix whose sum is 0182
806Linked List Cycle182
807Maximum Depth of N-ary Tree Leetcode Solution182
808Remove Nth Node From End of List Leetcode Solution182
809Longest Subarray Having Count of 1s One More than Count of 0s182
810Invert Binary Tree LeetCode Solution182
811One Edit Distance LeetCode Solution182
812Count items common to both the lists but with different prices181
813Balanced Expression with Replacement181
814Final Prices With a Special Discount in a Shop Leetcode Solution181
815Number of Islands II LeetCode Solution181
816Circular Queue181
817Identify and Mark Unmatched Parenthesis in an Expression181
818Nested List Weight Sum II LeetCode Solution180
819Transpose Graph180
820Minimum time required to rot all oranges180
821Repeated Substring Pattern LeetCode Solution180
822Diagonal Traversal of Binary Tree180
823Given an Array of Pairs Find all Symmetric Pairs in it180
824Relative Ranks Leetcode Solution180
825Make Two Arrays Equal by Reversing Sub-arrays Leetcode Solution179
826Minimum Jumps to Reach Home LeetCode Solution179
827Deletion in a Binary Tree179
828Reorder Data in Log Files LeetCode Solution179
829Minimum Swaps to Make Strings Equal Leetcode Solution179
830Search a 2D Matrix II Leetcode Solution179
831Minimum Number of Taps to Open to Water a Garden LeetCode Solution179
832Crawler Log Folder Leetcode Solution179
833LCS (Longest Common Subsequence) of three strings179
834Permutation Coefficient179
835Daily Temperatures Leetcode Solution179
836Distinct adjacent elements in an array178
837Split Array Into Consecutive Subsequences178
838Number Complement Leetcode Solution178
839Sort Array By Parity II Leetcode Solution178
840Subsequence of Size K With the Largest Even Sum LeetCode Solution178
841Course Schedule II – LeetCode178
842Remove Duplicates from Sorted List II178
843Clone Graph LeetCode Solution178
844Design Browser History LeetCode Solution178
845Missing Element in Sorted Array LeetCode Solution178
846Last Stone Weight II LeetCode Solution178
847Subarray Product Less Than K LeetCode Solution178
848Find Maximum Sum Possible Equal Sum of Three Stacks177
849Insert Delete GetRandom177
850Binary Search Tree Search and Insertion177
851A Space Optimized DP solution for 0-1 Knapsack Problem177
852Check if an Array is Stack Sortable177
853Check if stack elements are pairwise consecutive177
854Sliding Window Maximum177
855Lemonade Change Leetcode Solution177
856Iterative Preorder Traversal177
857Find all permuted rows of a given row in a matrix177
858Find the Only Repetitive Element Between 1 to N-1176
859Minimum Sum Path in a Triangle176
860Guess Number Higher or Lower LeetCode Solution176
861Check if a given array can represent Preorder Traversal of Binary Search Tree176
862Matrix Chain Multiplication176
863Alien Dictionary LeetCode Solution176
864Path with maximum average value176
865Tree Traversal (Preorder, Inorder & Postorder)176
866Count Distinct Elements in Every Window of Size K176
867Subset with sum divisible by m176
868Valid Parentheses Leetcode Solution176
869Minimum number of jumps to reach end176
870An Interesting Method to generate Binary Numbers from 1 to n176
871Partition List Leetcode Solution176
872Find the subarray with least average176
873Union and Intersection of two Linked Lists176
874Minimum swaps to make sequences increasing175
875Remove Duplicates from Sorted List LeetCode Solution175
876Count ways to reach the nth stair using step 1, 2 or 3175
877Dividing Array into Pairs With Sum Divisible by K175
878Interval Tree175
879Design a Stack With Increment Operation Leetcode Solution175
880Convert BST to Min Heap175
881Sorted Array to Balanced BST175
882Can Place Flowers LeetCode Solution175
883Get Maximum in Generated Array Leetcode Solution175
884Spiral Matrix II Leetcode Solution175
885Sum of nearest smaller and greater number175
886Check whether a given Binary Tree is Complete or not174
887GCDs of given index ranges in an array174
888Minesweeper LeetCode Solution174
889Infix to Postfix174
890Number of Distinct Islands Leetcode Solution174
891Sort Colors174
892Level order Traversal in Spiral Form174
893Brightest Position on Street LeetCode Solution174
894Sequences of given length where every element is more than or equal to twice of previous174
895Least Number of Unique Integers after K Removals Leetcode Solution174
896Range sum queries without updates173
897Friends Pairing Problem173
898Time Based Key-Value Store LeetCode Solution173
899Maximum Score After Splitting a String Leetcode Solution173
900Shortest Word Distance Leetcode Solution173
901Maximum size subarray sum equals k173
902Diagonal Traverse LeetCode Solution173
903Median of Two Sorted Arrays173
904Water Bottles Leetcode Solution173
905Diagonal Traversal LeetCode Solution173
906Rearrange Array such that arr[i] >= arr[j] if i is even and arr[i] <= arr[j] if i is odd and j < i173
907Destination City Leetcode Solution173
908Find all triplets with zero sum173
909Guess Number Higher or Lower II173
910Iterative Postorder Traversal Using Two Stacks173
911Best Time to Buy and Sell Stock with Transaction Fee Leetcode Solution173
912Pattern Occurrences using Stack173
913Find distance between two nodes of a Binary Tree173
914Robot Bounded In Circle LeetCode Solution172
915Set Matrix Zeroes Leetcode Solution172
916Check if any two intervals overlap among a given set of intervals172
917Rearrange an Array Such that arr[i] is equal to i172
918Delete And Earn172
919Insert into a Binary Search Tree Leetcode Solution172
920Lexicographical Numbers Leetcode Solution172
921Count Negative Numbers in a Sorted Matrix LeetCode Solution172
922Range LCM Queries172
923A program to check if a binary tree is BST or not171
924Averages of Levels in Binary Tree171
925Alien Dictionary171
926All Unique Triplets that Sum up to a Given Value171
927Difference Array | Range update query in O(1)171
928Three way partitioning of an array around a given range170
929My Calendar I LeetCode Solution170
930Find Common Characters Leetcode Solution170
931Rearrange Spaces Between Words Leetcode Solution170
932Count Submatrices With All Ones LeetCode Solution170
933K’th Largest Element in BST when modification to BST is not allowed170
934Construct the Rectangle Leetcode Solution170
935Spiral Matrix III LeetCode Solution170
936Construct Complete Binary Tree from its Linked List Representation170
937Analyze User Website Visit Pattern LeetCode Solution170
938Count Subarrays with Same Even and Odd Elements170
939Binary Tree Longest Consecutive Sequence LeetCode Solution170
940Special Positions in a Binary Matrix Leetcode Solution170
941Check if the given array can represent Level Order Traversal of Binary Search Tree170
942Product of Array Except Self LeetCode Solution170
943Intersection of Two Linked Lists LeetCode Solution169
944Minimum Height Trees LeetCode Solution169
945Create Maximum Number169
946Merge Two Sorted Lists Leetcode169
947Queue using Stacks169
948Trim a Binary Search Tree169
949Number of Equivalent Domino Pairs Leetcode Solution169
950Three Consecutive Odds Leetcode Solution169
951Binary array after M range toggle operations169
952Remove Duplicates from Sorted List II LeetCode Solution169
953Convert Sorted List to Binary Search Tree169
954Palindrome Partitioning Leetcode Solution169
955Vertical sum in a given binary tree169
956Maximum Frequency Stack Leetcode Solution169
957Word Break168
958Maximize Sum of Array after K Negations Leetcode Solution168
959Longest Palindromic Subsequence168
960BFS for Disconnected Graph168
961Queries for GCD of all numbers of an array except elements in a given range168
962Largest area rectangular sub-matrix with equal number of 1’s and 0’s168
963Strongly Connected Component168
964Count subarrays where second highest lie before highest167
965Longest subsequence such that difference between adjacents is one167
966Count Primes in Ranges167
967Reverse Nodes in K-Group167
968Climbing stairs167
9693 Sum167
970Depth First Search (DFS) for a Graph167
971Sign of the Product of an Array LeetCode Solution167
972Maximum Product Subarray167
974Construct BST from its given Level Order Traversal167
975Kth Smallest Element in a BST Leetcode Solution167
976Print Fibonacci sequence using 2 variables166
977Count pair with Given Sum166
978Unique Paths II166
979Combination Sum IV LeetCode Solution166
980Merging Intervals166
981Number of palindromic paths in a matrix166
982Symmetric Tree166
983Stone Game II Leetcode166
984Design Hit Counter LeetCode Solution165
985Find Maximum of Minimum for Every Window Size in a Given Array165
986Breadth First Search (BFS) for a Graph165
987Maximum Subarray Sum Excluding Certain Elements165
988String Matching in an Array Leetcode Solution165
989Longest Nice Substring LeetCode Solution165
990Scramble String LeetCode Solution165
991Largest Number Leetcode Solution165
992Serialize and Deserialize Binary Tree165
993Find number of pairs in an array such that their XOR is 0165
994The Maze III LeetCode Solution165
995Can Make Arithmetic Progression From Sequence Leetcode Solution164
996Largest Substring Between Two Equal Characters Leetcode Solution164
997Palindrome Partitioning164
998Maximum Product of Indexes of Next Greater on Left and Right164
999Valid Boomerang Leetcode Solution164
1000Asteroid Collision LeetCode Solution164
1001Maximum Length of Repeated Subarray164
1002Next Permutation Leetcode Solution164
1003Find the First Circular Tour that visits all the Petrol Pumps164
1004Binary Search Tree Delete Operation164
1005Height of a generic tree from parent array164
1006Find the Difference Leetcode Solution164
1007K maximum sums of overlapping contiguous sub-arrays163
1008Consecutive Characters LeetCode Solution163
1009K Closest Points to Origin Leetcode Solution163
1010Graph Valid Tree LeetCode Solution163
1011Remove Duplicates from Sorted Array II Leetcode Solution163
1012Balanced Binary Tree163
1013Count pairs from two sorted arrays whose sum is equal to a given value x163
1014The Painter’s Partition Problem163
1015Shortest Completing Word Leetcode Solution163
1016Print Next Greater Number of Q queries163
1017Kth Smallest Element in a Sorted Matrix LeetCode Solution163
1018Find postorder traversal of BST from preorder traversal162
1019Generate Parentheses Leetcode Solution162
1020Length of Longest Fibonacci Subsequence162
1021Maximum difference between frequency of two elements such that element having greater frequency is also greater162
1022Collect maximum points in a grid using two traversals162
1023Minimum Index Sum of Two Lists162
1024Invalid Transactions LeetCode Solution162
1025Maximum Number of Ways to Partition an Array LeetCode Solution162
1026Decrypt String from Alphabet to Integer Mapping Leetcode Solution162
1027Newman-Conway Sequence162
1028Validate Binary Search Tree162
1029Level Order Traversal of Binary Tree162
1030Maximum length subsequence with difference between adjacent elements as either 0 or 1162
1031Shuffle 2n integers as without using extra space162
1032Friends Of Appropriate Ages LeetCode Solution162
1033Maximum Sum of 3 Non-Overlapping Subarrays162
1034Find a Peak Element II LeetCode Solution161
1035Make The String Great Leetcode Solution161
1036Number Of Longest Increasing Subsequence161
1037Move all negative elements to end in order with extra space allowed161
1038Largest divisible pairs subset161
1039Available Captures for Rook Leetcode Solution161
1040Merge Sort161
1041Rearrange an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’161
1042Boolean Parenthesization Problem161
1043Find Duplicate Subtrees161
1044Check If a Word Occurs As a Prefix of Any Word in a Sentence Leetcode Solution161
1045Next Greater Element III LeetCode Solution161
1046Segment Tree161
1047Insertion in a Binary Tree160
1048Bitwise AND of Numbers Range LeetCode Solution160
1049Construct Binary Tree from given Parent Array representation160
1050Custom Sort String Leetcode Solution160
1051Kill Process LeetCode Solution160
1052First missing positive160
1053Advantages of BST over Hash Table160
1054Build an Array With Stack Operations Leetcode Solution160
1055Construction of Longest Increasing Subsequence (N log N)160
1056Compute nCr % p160
1057Binary Search Tree160
1058Boundary Traversal of binary tree159
1059Print Right View of a Binary Tree159
1060Iterative Depth First Traversal of Graph159
1061Rearrange array such that even positioned are greater than odd159
1062Determine Whether Matrix Can Be Obtained By Rotation LeetCode Solution159
1063Count minimum steps to get the given desired array159
1064Rearrange array such that even index elements are smaller and odd index elements are greater159
1065Maximum subsequence sum such that no three are consecutive158
1066Double the first element and move zero to end158
1067Find Peak Element158
1068Partition Equal Subset Sum158
1069Defanging an IP Address LeetCode Solution158
1070Subarrays with K Different Integers Leetcode Solution158
1071Largest BST Subtree LeetCode Solution158
1072Minimum Size Subarray Sum158
1073Employee Importance LeetCode Solution158
1074Path Sum II LeetCode Solution158
1075Maximum weight transformation of a given string157
1076Regular Expression Matching Regular Expression Matching LeetCode Solution157
1077Remove Palindromic Subsequences Leetcode Solution157
1078Add two numbers157
1079Morris Inorder Traversal157
1080Smallest Common Region Leetcode Solution157
1081Recover Binary Search Tree Leetcode Solution157
1082Level order traversal using two Queues157
1083Find maximum difference between nearest left and right smaller elements157
1084Binary Tree Right Side View LeetCode Solution156
1085Ugly Numbers156
1086Longest Bitonic Subsequence156
1087Ugly Number II LeetCode Solution156
1088Lowest Common Ancestor156
1089Remove duplicates from sorted array156
1090Find whether a subarray is in form of a mountain or not156
1091Palindrome Permutation LeetCode Solution156
1092Implement Trie (Prefix Tree) Leetcode Solution156
1093Palindromic Substrings Leetcode Solution155
1094Super Ugly Number155
1095Bus Routes Leetcode Solution155
1096Increasing Triplet Subsequence LeetCode Solution155
1097Populating Next Right Pointers in Each Node Leetcode Solution155
1098Maximize Distance to Closest Person LeetCode Solution155
1099Number of siblings of a given Node in n-ary Tree155
1100Number of Closed Islands Leetcode Solution155
1101Divisible Pairs Counting154
1102Valid Tic-Tac-Toe State LeetCode Solution154
1103Print all triplets in sorted array that form AP154
1104Iterative method to find ancestors of a given binary tree154
1105Construct Binary Tree from Preorder and Postorder Traversal LeetCode Solution154
1106Path Sum154
1107Reformat The String Leetcode Solution154
1108Sum of Even Numbers After Queries154
1109Find the minimum distance between two numbers153
1110Binary Tree Data Structure153
1111Find Three Element From Different Three Arrays Such That a + b + c = sum153
1112Search in Sorted Rotated Array153
1113Day of the Year Leetcode Solution153
1114Thousand Separator Leetcode Solution153
1115Moser-de Bruijn Sequence153
1116Kth Smallest Product of Two Sorted Arrays LeetCode Solution152
1117Count Largest Group Leetcode Solution152
1118Mean of Array After Removing Some Elements Leetcode Solution152
1119Search Insert Position152
1120Level of Each node in a Tree from source node152
1121Products of ranges in an array152
1122Minimum Absolute Difference in BST Leetcode Solution152
1123Find Smallest Range Containing Elements from k Lists152
1124Cells with Odd Values in a Matrix LeetCode Solution152
1125Number of Students Doing Homework at a Given Time Leetcode Solution152
1126Root to Leaf path with target sum Leetcode Solutions152
1127Distinct Subsequences151
1128Longest Increasing Consecutive Subsequence151
1129Clone a Binary Tree with Random Pointers151
1130Bottom View of a Binary Tree151
1131Serialize and Deserialize Binary Tree LeetCode Solution151
1132Minimum Moves to Equal Array Elements LeetCode Solution150
1133Convert BST into a Min-Heap without using array150
1134Construct K Palindrome Strings LeetCode Solution150
1135Maximum Product of Splitted Binary Tree LeetCode Solution150
1136Closest Leaf in a Binary Tree LeetCode Solution150
1137Constant time range add operation on an array150
1138Compare Strings by Frequency of the Smallest Character Leetcode Solution150
1139Longest Subarray of 1’s After Deleting One Element LeetCode Solution150
1140Third Maximum Number Leetcode Solution150
1141Topological Sorting150
1142Find maximum length Snake sequence150
1143Find Two Non-overlapping Sub-arrays Each With Target Sum LeetCode Solution150
1144Prime Palindrome LeetCode Solution150
1145Minimum sum of squares of character counts in a given string after removing k characters150
1146Write Code to Determine if Two Trees are Identical150
1147Maximum Product Subarray150
1148Diameter of N-Ary Tree LeetCode Solution149
1149Golomb sequence149
1150Rotate Array149
1151Maximum Depth Of Binary Tree149
1152Queries for Number of Distinct Elements in a Subarray149
1153Longest Repeated Subsequence149
1154Swap Nodes In Pairs148
1155Print modified array after executing the commands of addition and subtraction148
1156Priority Queue148
1157Reformat Date LeetCode Solution148
1158Search Suggestions System LeetCode Solution148
1159Count even length binary sequences with same sum of first and second half bits148
1160Subset Sum Problem in O(sum) space148
1161Web Crawler LeetCode Solution148
1162Minimum Score Triangulation of Polygon Leetcode Solution148
1163Search an Element in Sorted Rotated Array148
1164Cutting a Rod147
1165Maximize sum of consecutive differences in a circular array147
1166Find a sorted subsequence of size 3 in linear time147
1167Closest Binary Search Tree Value Leetcode Solution147
1168Contiguous Array LeetCode Solution147
1169Delete Nodes and Return Forest Leetcode Solution147
1170Find Largest Value in Each Tree Row LeetCode Solution147
1171Matchsticks to Square Leetcode Solution146
1172Given a binary tree, how do you remove all the half nodes?146
1173Kth Smallest Number in Multiplication Table Leetcode Solution146
1174Count Pairs Whose Products Exist in Array146
1175Red-Black Tree Introduction146
1176Minimum Cost to Move Chips to The Same Position LeetCode Solution146
1177Transform a BST to Greater sum Tree146
1178Minimum Sideway Jumps LeetCode Solution145
1179Minimum Swaps To Make Sequences Increasing LeetCode Solution145
1180K’th Largest element in BST using constant extra space145
1181Decision Tree145
1182Maximum sum of a path in a Right Number Triangle145
1183Possible Bipartition LeetCode Solution145
1184Decrease Elements To Make Array Zigzag LeetCode Solution144
1185Sum of Left Leaves LeetCode Solution144
1186Remove Max Number of Edges to Keep Graph Fully Traversable Leetcode Solution144
1187Factorial Trailing Zeroes LeetCode Solution144
1188Maximum Value at a Given Index in a Bounded Array LeetCode Solution144
1189Valid Triangle Number144
1190Path Crossing Leetcode Solution144
1191Replace two consecutive equal values with one greater144
1192Merge two BSTs with limited extra space144
1193Maximum number of segments of lengths a, b and c144
1194Check Array Formation Through Concatenation Leetcode Solution144
1195Maximum Binary Tree144
1196Find the smallest binary digit multiple of given number144
1197Binary Tree to Binary Search Tree Conversion144
1198First Bad Version144
1199Reverse a Path in BST using Queue144
1200Number of Orders in the Backlog Leetcode Solution143
1201Perfect Squares LeetCode Solution143
1202Maximum sum bitonic subarray143
1203Convert Integer to the Sum of Two No-Zero Integers Leetcode Solution143
1204Maximum sum of pairs with specific difference143
1205Print n terms of Newman-Conway Sequence143
1206Concatenation of Array LeetCode Solution143
1207Convert Sorted Array to Binary Search Tree LeetCode Solutions142
1208Queue Reconstruction by Height142
1209Queries on Probability of Even or Odd Number in given Ranges142
1210Swapping Nodes in a Linked List Leetcode Solution142
1211Valid Perfect Square LeetCode Solution142
1212Sliding Window Median Leetcode Solution142
1213Divide Two Integers Leetcode Solution142
1214New 21 Game141
1215Guess The Word141
1216Integer Break LeetCode Solution141
1217How to print maximum number of A’s using given four keys141
1218Graph and its representation140
1219Lowest Common Ancestor of a Binary Tree Leetcode Solution140
1220Find minimum number of merge operations to make an array palindrome140
1221Array Queries for multiply replacements and product140
1222Lowest Common Ancestor in Binary Search Tree140
1223Kth Smallest Element in a BST140
1224Champagne Tower LeetCode Solution140
1225Moving Stones Until Consecutive Leetcode Solution139
1226Longest Common Prefix Using Word by Word Matching139
1227Merge k Sorted Lists Leetcode Solution139
1228Flatten 2D Vector LeetCode Solution139
1229Check if all levels of two Binary Tree are anagrams or not139
1230Range Sum Query using Sparse Table139
1231Maximum Array from Two given Arrays Keeping Order Same139
1232The kth Factor of n Leetcode Solution138
1233Contiguous Array138
1234Design Skiplist LeetCode Solution138
1235Filter Restaurants by Vegan-Friendly, Price and Distance Leetcode Solution138
1236Write a function to get the intersection point of two Linked Lists138
1237Find Minimum in Rotated Sorted Array II LeetCode Solution138
1238Mean of range in array138
1239BST to a Tree with Sum of all Smaller Keys137
1240Maximize Elements Using Another Array137
1241Largest Plus Sign Leetcode Solution137
1242Maximum Sum Increasing Subsequence137
1243Bold Words in String LeetCode Solution137
1244Missing Number137
1245Range Queries for Longest Correct Bracket Subsequence137
1246Print modified array after multiple array range increment operations137
1247LRU Cache Leetcode Solution137
1248Find k-th smallest element in BST (Order Statistics in BST)136
1249Minimum Remove to Make Valid Parentheses LeetCode Solution136
1250Maximum Product Subarray136
1251Min Cost Climbing Stairs LeetCode Solution136
1252Parallel Courses II LeetCode Solution136
1253Count Subsets Having Distinct Even Numbers136
1254Graph Cloning135
1255Power of Two135
1256Check in binary array the number represented by a subarray is odd or even135
1257Image Overlap LeetCode Solution134
1258Minimum Time to Collect All Apples in a Tree LeetCode Solution134
1259Different Ways to Add Parentheses Leetcode Solution134
1260Verify Preorder Serialization of a Binary Tree134
1261Check if each internal node of a BST has exactly one child134
1262Arithmetic Slices II – Subsequence LeetCode Solution134
1263Check if two nodes are on the same path in a Tree133
1264Check Completeness of a Binary Tree LeetCode Solution133
1265Check for Identical BSTs without building the trees133
1266Smallest Range II Leetcode Solution133
1267Symmetric Tree LeetCode Solution Leetcode Solution132
1268Print Ancestors of a Given Binary Tree Node Without Recursion132
1269Koko Eating Bananas LeetCode Solution132
1270Longest Substring Without Repeating Characters Leetcode Solution132
1271Orderly Queue LeetCode Solution132
1272Next greater element131
1273Excel Sheet Column Title LeetCode Solution131
1274Arranging Coins Leetcode Solution130
1275Vertical Order Traversal of Binary Tree LeetCode Solution129
1276Number of elements less than or equal to a given number in a given subarray129
1277Merge Sorted Array129
1278Count and Toggle Queries on a Binary Array129
1279Palindrome Partitioning128
1280Largest Submatrix With Rearrangements LeetCode Solution128
1281Array Nesting Leetcode Solution127
1282Palindrome Number LeetCode Solution127
1283Newman–Shanks–Williams prime126
1284Maximum product of an increasing subsequence126
1285Check If a String Can Break Another String Leetcode Solution126
1286Peeking Iterator LeetCode Solution126
1287Add Two Numbers II Leetcode Solution126
1288Find the Winner of the Circular Game LeetCode Solution126
1289Insert Delete GetRandom O(1) Leetcode Solution125
1290Range Minimum Query (Square Root Decomposition and Sparse Table)125
1291Queries for Decimal Values of Subarrays of a Binary Array125
1292Check if X can give change to every person in the Queue125
1293Find maximum average subarray of k length124
1294Number of Subsequences That Satisfy the Given Sum Condition LeetCode solution123
1295Continuous Subarray Sum LeetCode Solution123
1296Encoded String With Shortest Length LeetCode Solution123
1297Check given array of size n can represent BST of n levels or not123
1298Jump Game IV LeetCode Solution121
1299Random Pick Index LeetCode Solution121
1300Number of indexes with equal elements in given range120
1301Reach a Number LeetCode Solution120
1302Binary Tree to Binary Search Tree Conversion using STL set120
1303Minimum Possible Integer After at Most K Adjacent Swaps On Digits LeetCode Solution120
1304Minimum Number of People to Teach LeetCode Solution120
1305Convert a BST to a Binary Tree such that sum of all greater keys is added to every key118
1306Minimum Total Space Wasted With K Resizing Operations LeetCode Solution117
1307Design A Leaderboard Leetcode Solution116
1308Convert to Base -2 LeetCode Solution116
1309Queries on XOR of greatest odd divisor of the range115
1310Design Underground System Leetcode Solution114
1311Shifting Letters LeetCode Solution112
1312Print Maximum Length Chain of Pairs111
1313Detect Capital Leetcode Solution111
1314Minimum Swaps to Group All 1’s Together Leetcode Solution110
1315Top K Frequent Elements LeetCode Solution110
1316Minimum Path Sum Leetcode Solution108
1317Count Sub Islands LeetCode Solution108
1318Substring with Concatenation of All Words Leetcode Solution107
1319Odd Even Linked List Leetcode Solution106
1320Monotonic Array Leetcode Solution105
1321Longest Common Subsequence LeetCode Solution102
1322Decode String Leetcode Solution101
1323Binary Tree Inorder Traversal LeetCode Solution101
1324Find the Town Judge LeetCode Solution100
1325Maximum Population Year LeetCode Solution100
1326Shortest Unsorted Continuous Subarray LeetCode Solution96
1327Rectangle Overlap LeetCode Solution95
1328Best Meeting Point LeetCode Solution94
1329Maximum Population Year LeetCode Solution93
1330Flatten Binary Tree to Linked List LeetCode Solution92
1331Find the Town Judge LeetCode Solution92
1332Insert into a Sorted Circular Linked List LeetCode Solution91
1333Sum Root to Leaf Numbers LeetCode Solution91
1334Design Add and Search Words Data Structure LeetCode Solution90
1335Stone Game IV LeetCode Solution88
1336Reveal Cards In Increasing Order Leetcode Solution88
1337Is Graph Bipartite? LeetCode Solution87
1338Range Sum Query 2D – Immutable LeetCode Solution87
1339Valid Triangle Number LeetCode Solution86
1340Score of Parenthesis LeetCode Solution85
1341Divide Chocolate LeetCode Solution81
1342Step-By-Step Directions From a Binary Tree Node to Another LeetCode Solution76
1343Range Sum of BST LeetCode Solution70
1344Reverse Integer Leetcode Solution68
1345Rotate String LeetCode Solution64
1346Find K Closest Elements LeetCode Solution64
1347Sort Colors LeetCode Solution63
1348Maximum Side Length of a Square with Sum Less than or Equal to Threshold LeetCode Solution61
1349Excel Sheet Column Number LeetCode Solution57
1350Maximum Size Subarray Sum Equals k Leetcode Solution51
1351H-Index Leetcode Solution46
1352Camelcase Matching Leetcode Solution45
1353Valid Anagram Leetcode Solution44
1354High Five LeetCode Solution43
1355Most Stones Removed with Same Row or Column LeetCode Solution43
1356Container With Most Water LeetCode Solution43
1357Group Anagrams LeetCode Solution42
1358Sliding Window Maximum LeetCode Solution42
1359Next Permutation LeetCode Solution41
1360Find Peak Element LeetCode Solution40
1361Binary Search LeetCode Solution40
1362Pairs of Songs With Total Durations Divisible by 60 LeetCode Solution39
1363Paint House LeetCode Solution37
1364Valid Triangle Number LeetCode Solution36
1365Minimum Number of Arrows to Burst Balloons LeetCode Solution36
1366Unique Binary Search Trees LeetCode Solution35
1367Flatten Binary Tree to Linked List LeetCode Solution35
1368Isomorphic Strings LeetCode Solution35
1369Next Greater Element I Leetcode Solution35
1370Count Good Nodes in Binary Tree LeetCode Solution34
1371Sentence Screen Fitting LeetCode Solution34
1372The Number of Weak Characters in the Game LeetCode Solution34
1373Group Shifted Strings Leetcode Solution34
1374Split Linked List in Parts Leetcode Solution32
1375Swim in Rising Water LeetCode Solution32
1376Insert Delete GetRandom O(1) – Duplicates allowed LeetCode Solution32
1377Single Element in a Sorted Array LeetCode Solution31
1378Closest Binary Search Tree Value II LeetCode Solution31
1379Peak Index in a Mountain Array LeetCode Solution31
1380All Possible Full Binary Trees LeetCode Solution28
1381Find First and Last Position of Element in Sorted Array LeetCode Solution28
1382Minimum Increment to Make Array Unique Leetcode Solution27
1383Lowest Common Ancestor of a Binary Search Tree Leetcode Solution27
1384Validate Stack Sequences LeetCode Solution27
1385Max Sum of Two Non-Overlapping Subarrays LeetCode Solution27
1386Best Time to Buy and Sell Stock IV LeetCode Solution27
1387Break a Palindrome LeetCode Solution25
1388Implement strStr() LeetCode Solution25
1389Detect Squares LeetCode Solution25
1390Implement Rand10() Using Rand7() Leetcode Solution24
1391Trapping Rain Water II LeetCode Solution24
1392Greatest Sum Divisible by Three LeetCode Solution24
1393Stone Game IV LeetCode Solution23
1394Invert Binary Tree LeetCode Solution22
1395Remove All Ones With Row and Column Flips Leetcode Solution22
1396Contains Duplicate LeetCode Solution22
1397Fibonacci Number LeetCode Solution21
1398Reverse Nodes in k-Group LeetCode Solution21
1399Minimum Number of Operations to Move All Balls to Each Box LeetCode Solution20
1400Design Bounded Blocking Queue LeetCode Solution19
1401Total Hamming Distance LeetCode Solution16
1402Candy LeetCode Solution16
1403Unique Paths III LeetCode Solution14
Translate »