Step-by-step solutions to popular LeetCode problems with pattern analysis and complexity breakdowns.
451 articles
LeetCode 933 Number of Recent Calls requires a RecentCounter that counts pings within a 3000ms sliding window. The queue-based solution maintains only timestamps in [t-3000, t] by dequeuing expired entries from the front after each ping. Because timestamps are strictly increasing, expired entries are always at the front — a simple while loop handles the window. Each timestamp enters and exits the queue exactly once, giving O(1) amortized time and making this an ideal introduction to sliding window queue design.
Master LeetCode 374 Guess Number Higher or Lower with clean binary search. Learn how the guess API replaces array comparisons, how to handle counterintuitive return values, and the overflow-safe mid calculation in O(log n) time.
Solve LeetCode 201 Bitwise AND of Numbers Range in O(log n) using right-shift alignment or the Brian Kernighan trick to isolate the common binary prefix of left and right.
Master LeetCode 36 Valid Sudoku by encoding row, column, and box constraints as tuple keys in a single set. One pass, three key types per cell, and integer division by 3 to map cells to their 3x3 box. O(1) time and space since the board is always 9x9.
LeetCode 26 Remove Duplicates from Sorted Array asks you to remove duplicates in-place from a sorted array and return the count of unique elements. The two-pointer approach uses slow as the write head and fast as the read head: when fast finds a value different from nums[slow], copy it to nums[slow+1] and advance slow. Return slow+1 as the unique count.
Learn how to reverse a sublist in a singly linked list between positions left and right in a single pass using a dummy node and the pull-to-front pointer technique for LeetCode 92.
Master LeetCode 438 Find All Anagrams in a String with a fixed-size sliding window, frequency arrays, and a matches counter that tracks how many of the 26 characters have equal counts between the window and pattern — achieving O(n) time and O(1) space.
LeetCode 383 Ransom Note asks whether a ransom note string can be constructed from the characters of a magazine string, using each magazine character at most once. The optimal approach counts character frequencies in the magazine, then checks that every character in the ransom note has sufficient supply. Python Counter subtraction and a Java int[26] array both solve this in O(n+m) time and O(1) space.
Master LeetCode 2336 Smallest Number in Infinite Set using a counter plus a sorted set. Learn why this hybrid structure gives O(log n) popSmallest and addBack operations.
Solve LeetCode 130 Surrounded Regions with the reverse thinking trick. DFS from border O's to mark safe cells, then flip all unmarked O's to X — cleaner and faster than tracking surrounded regions directly.
LeetCode 148 Sort List asks you to sort a linked list in O(n log n) time. The optimal approach is merge sort: use the fast/slow pointer technique to find the middle, disconnect the list into two halves, recursively sort each half, and merge them using the classic merge-two-sorted-lists subroutine. The top-down recursive approach uses O(log n) stack space; the bottom-up iterative approach satisfies the O(1) space follow-up by merging sublists of increasing sizes without any recursion.
LeetCode 3 asks for the length of the longest substring without repeating characters. The optimal solution uses a sliding window with a hashmap storing each character's last seen index. When a duplicate is found, the left pointer jumps directly to max(left, lastIndex[char] + 1), achieving true O(n) single-pass performance instead of O(2n) for the hashset shrink variant.
Solve LeetCode 143 Reorder List by breaking it into three well-known linked list operations: find middle, reverse second half, and merge alternating. Each step is independently testable and together they give an O(n) time O(1) space solution.
Solve LeetCode 994 Rotting Oranges with multi-source BFS. Enqueue all rotten oranges at once, spread rot level-by-level, and count minutes until no fresh orange remains or return -1.
Solve LeetCode 2542 Maximum Subsequence Score by sorting index pairs by nums2 descending, then using a min-heap of size k to greedily keep the top nums1 values and compute the maximum sum * min product.
Master LeetCode 853 Car Fleet by sorting cars by position descending, computing arrival times as (target - position) / speed, and using a stack to count distinct fleets. If a car arrives before or at the same time as the fleet ahead, it merges. O(n log n) time, O(n) space. Full Python and Java walkthroughs included.
Master LeetCode 752 Open the Lock with BFS on a state-space graph. Explore all 10,000 possible dial states, avoid deadends, and find the shortest path to the target combination.
Master LeetCode 42 Trapping Rain Water with three approaches: precompute prefix max arrays for an O(n) solution, reduce space to O(1) with two pointers, or use a monotonic stack to compute trapped water layer by layer.
LeetCode 136 Single Number asks you to find the one element that appears exactly once when every other element appears twice. XOR is the perfect tool: a^a = 0 and a^0 = a, so XOR-ing all elements together cancels every duplicate pair, leaving only the unique number. This deep dive covers why XOR works, all alternative approaches, and a full walk-through example.
Solve LeetCode 142 Linked List Cycle II in O(n) time and O(1) space using Floyd's algorithm: phase one detects whether a cycle exists, phase two finds the exact node where the cycle begins. The math behind why it works is the real insight.
Solve LeetCode 137 Single Number II by building a two-variable bitwise state machine that counts each bit position mod 3. When XOR alone fails for triplets, ones and twos track the 1-mod-3 and 2-mod-3 states, cancelling bits that appear three times and leaving only the unique element.
Solve LeetCode 134 Gas Station in O(n) with one-pass greedy. Track running tank deficit and total gas-cost balance to find the unique valid start without trying every station.
Solve LeetCode 2462 Total Cost to Hire K Workers by maintaining two min-heaps — one for the first candidates workers and one for the last candidates — picking the cheapest available candidate each round and refilling from the middle as workers are hired.
Master LeetCode 271 Encode and Decode Strings with length-prefix encoding. Prepend each string with its character count and a "#" delimiter, then decode by reading the count, skipping "#", and slicing exactly that many characters. Handles any input including strings with "#", commas, and newlines.
Master LeetCode 217 Contains Duplicate with two approaches: O(n) HashSet membership checking with early exit and O(n log n) sorting for adjacent comparison. Covers the Python one-liner, Java HashSet.add() return value trick, early exit optimization, and the space-vs-time trade-off interviewers expect you to discuss.
LeetCode 208 Implement Trie asks you to design a data structure that supports inserting words and querying whether a full word or a prefix exists. A Trie (prefix tree) solves this by building a tree of TrieNode objects where each node represents one character. Insert walks the tree creating nodes as needed and marks the final node as an end-of-word marker. Search traverses the tree and checks the isEnd flag. StartsWith only checks whether traversal completes. All three operations run in O(m) time where m is the word length — dramatically faster than scanning a list of n words at O(m * n) per query.
LeetCode 9 Palindrome Number asks whether an integer reads the same forwards and backwards. The naive approach converts to a string and checks equality, but the follow-up asks you to solve it without string conversion. The optimal approach reverses only the second half of the digits using the pop-and-push technique, then compares the reversed half to the remaining first half — stopping when the reversed portion is at least as large as x. For even-length palindromes the two halves must be equal; for odd-length palindromes the middle digit is discarded with integer division by 10. Quick rejects handle negatives and numbers ending in zero in O(1).
LeetCode 680 asks whether a string can become a palindrome by deleting at most one character. The two-pointer approach scans inward until a mismatch is found, then checks two candidate substrings: skip the left character or skip the right character. If either substring is a palindrome, return true. The greedy insight is that the first mismatch pinpoints the only two substrings worth checking — no backtracking, no O(n^2) brute force needed.
LeetCode 1700 Students Unable to Eat Lunch asks how many students cannot eat given a queue of students with preferences and a stack of sandwiches. The naive approach simulates the rotation queue in O(n^2). The key insight: queue order is irrelevant — what matters is whether any remaining student wants the top sandwich. Counting preferences and scanning the stack gives an O(n) solution that is simpler, faster, and less error-prone than any rotation simulation.
Master LeetCode 138 Copy List with Random Pointer. Learn the hashmap approach for O(n) space, the elegant interleave-and-split trick for O(1) space, and recursive memoization — all explained with Python and Java walkthroughs.
Master LeetCode 371 Sum of Two Integers using XOR for the bitwise sum without carry and AND with left shift for carry propagation. Covers the iterative algorithm, why the loop terminates, two's complement for negatives, Python's 32-bit mask requirement, and full Python and Java implementations with O(1) time and space.
LeetCode 225 Implement Stack using Queues requires simulating LIFO order with only FIFO queue operations. The push-expensive rotation approach is the most interview-friendly: after enqueuing a new element, rotate all previous elements to the back so the new element sits at the front. This makes push O(n) and pop/top O(1). The single-queue variant does the same thing with one queue instead of two by rotating exactly size-1 elements after each push. A pop-expensive alternative exists — push O(1), pop O(n) by transferring elements — but is less common in practice.
Master LeetCode 332 Reconstruct Itinerary using Hierholzer's algorithm for Eulerian path traversal. DFS with post-order insertion and sorted adjacency lists guarantee the lexicographically smallest itinerary starting from JFK.
LeetCode 31 asks you to rearrange an integer array into the next lexicographically greater permutation in place with O(1) extra space. The three-step algorithm works by finding the rightmost index where nums[i] < nums[i+1] (the ascent), swapping nums[i] with the smallest value in the suffix that is still larger than it, and then reversing the suffix. If no ascent exists the array is already the largest permutation — just reverse the whole array to get the smallest. The key insight is that the suffix after the ascent is always in descending order, making the swap and reverse both O(n) in total.
Solve LeetCode 261 Graph Valid Tree by checking two conditions: the edge count must equal exactly n-1, and the graph must be fully connected. Union-Find detects cycles in near-constant time; DFS from node 0 confirms all nodes are reachable.
LeetCode 75 Sort Colors asks you to sort an array of 0s, 1s, and 2s in-place so all 0s come first, then 1s, then 2s. The naive two-pass counting sort works but the follow-up demands a single pass. The Dutch National Flag algorithm solves this with three pointers — low, mid, high — that maintain four invariant regions as they converge, sorting the array in one linear scan with constant extra space.
Learn how to solve LeetCode 328 Odd Even Linked List by separating nodes at odd and even index positions into two chains then reconnecting them for an in-place O(n) time O(1) space solution.
LeetCode 85 Maximal Rectangle asks you to find the largest rectangle of 1s in an m x n binary matrix. The key insight is to reduce the 2D problem to a sequence of 1D problems: treat each row as the ground of a histogram where heights[j] counts consecutive 1s in column j up to the current row (resetting to 0 whenever a 0 is encountered). Then apply the O(n) monotonic stack algorithm from LeetCode 84 to each row's histogram to find the maximum rectangle. Running this once per row gives an overall O(m*n) solution that processes every cell exactly once.
Master LeetCode 23 Merge K Sorted Lists with min-heap and divide-and-conquer approaches. Both achieve O(n log k) time complexity merging k sorted linked lists into one.
Master LeetCode 14 Longest Common Prefix with three approaches: vertical scanning stops at the first mismatch, horizontal reduction applies LCP iteratively, and sort-based optimization compares only the first and last strings after sorting for an elegant O(n log n) trick.
Solve LeetCode 2482 Difference Between Ones and Zeros in Row and Column by precomputing ones counts per row and column, then applying a simplified formula to build the diff matrix in O(m*n) time.
Solve LeetCode 210 Course Schedule II by extending Kahn's BFS to collect the topological order as you process each zero in-degree node. If the result contains all n courses, return it; otherwise a cycle exists — return an empty array.
Master LeetCode 743 Network Delay Time using Dijkstra's algorithm with a min-heap priority queue. Full walkthrough covering greedy shortest path, adjacency list, and Python/Java code.
Master LeetCode 895 Maximum Frequency Stack with the two-map design: a freqMap tracking each value's current frequency and a groupMap storing per-frequency stacks. Learn why a max-heap approach fails for tie-breaking by recency, how maxFreq updates in O(1) on push and pop, and why elements appear in multiple frequency stacks simultaneously.
Learn how to solve LeetCode 199 Binary Tree Right Side View with two clean approaches. BFS level-order traversal processes each level and captures the last element, which is always the rightmost node visible from the right side. DFS visits the right subtree before the left, so the first node seen at each new depth is the rightmost. Both run in O(n) time; BFS uses O(w) width space, DFS uses O(h) height space. Python and Java implementations included with a breakdown of the left side view variant.
Solve LeetCode 684 Redundant Connection using Union-Find cycle detection. Learn how to identify the first edge that creates a cycle in an undirected graph built from n nodes, with Python and Java implementations.
Master LeetCode 213 House Robber II by reducing the circular constraint to two linear House Robber I passes — rob houses 0..n-2 or 1..n-1 and take the maximum. O(n) time, O(1) space using two rolling variables per pass.
LeetCode 1512 asks how many (i,j) pairs exist where nums[i] == nums[j] and i < j. The key insight: instead of checking all pairs in O(n^2), count value frequencies and apply the combination formula k*(k-1)/2 to each frequency for an O(n) solution.
Master LeetCode 981 Time Based Key-Value Store. Learn why storing (timestamp, value) pairs per key lets you binary search for the largest timestamp <= query, with clean Python and Java implementations using bisect and Collections.binarySearch in O(log n) per get.
Solve LeetCode 11 Container With Most Water in O(n) time using two pointers. Understand the greedy proof, brute force baseline, and why you always move the shorter pointer.
Master LeetCode 1657 Determine if Two Strings Are Close by verifying two simple conditions: the character sets are identical and the sorted multisets of character frequencies match — no operation simulation needed.
Master LeetCode 2352 Equal Row and Column Pairs by hashing rows as tuples into a Counter, then iterating each column to look up its tuple — O(n^2) time with a clean two-pass solution.
Learn how to solve LeetCode 19 Remove Nth Node From End of List in a single pass using the two-pointer gap technique with a dummy head node.
LeetCode 362 Design Hit Counter asks you to implement a counter that tracks hits in the past 300 seconds. The queue approach is intuitive: store every timestamp and discard entries older than 300 seconds on each getHits call. The circular array approach is optimal: two arrays of size 300 indexed by timestamp % 300 give O(1) hit and O(300) = O(1) getHits with fixed memory. Follow-up questions cover thread safety for concurrent access — a common system design interview topic that builds directly toward rate limiter design.
Master LeetCode 18 4Sum by chaining reductions: fix two elements, then solve the inner 2Sum with two pointers. Learn duplicate skipping, pruning, and the general k-sum framework.
Master LeetCode 300 Longest Increasing Subsequence with two approaches: O(n^2) DP where dp[i] = max LIS ending at i, and O(n log n) patience sorting with binary search on a tails array. Both in Python and Java with full walkthroughs.
Master LeetCode 17 Letter Combinations of a Phone Number with backtracking: map each digit to its keypad letters, recurse through each digit position appending one letter at a time, and collect results when all digits are processed — or use iterative BFS expansion as an alternative.
Master LeetCode 211 Design Add and Search Words with a complete Trie plus DFS approach. Learn how to build a TrieNode with 26 children, insert words character by character, and implement a recursive wildcard search that branches across all children when it encounters a dot. Understand why a HashMap fails for wildcard queries, how to prune branches early for better practical performance, and how to avoid the common base-case bug that checks node existence instead of the isEnd flag.
Master LeetCode 872 Leaf-Similar Trees by running DFS on each binary tree to gather leaf values in order, then comparing the two sequences for equality — clean O(n+m) solution with a Python generator optimization.
Master LeetCode 700 Search in a BST with recursive and iterative approaches. Learn how BST ordering gives O(h) time by comparing the target with each node and navigating left or right until found or null.
Master LeetCode 1137 N-th Tribonacci Number using three rolling variables for O(n) time O(1) space: initialize a=0, b=1, c=1, then repeatedly compute next=a+b+c and shift — a direct Fibonacci variant that adds just one more variable to handle the three-term recurrence.
LeetCode 841 Keys and Rooms gives you n rooms labeled 0 to n-1 where room 0 starts unlocked and each room holds keys to other rooms. Starting from room 0, collect keys and visit rooms to determine if all rooms are reachable. The solution is a standard DFS or BFS graph traversal: treat rooms as nodes and keys as directed edges, traverse from node 0 with a visited set, and check if visited.size equals n. This reachability check is the core of many graph problems and appears across connected component and traversal families.
Solve LeetCode 518 Coin Change II by counting the number of combinations that make up a target amount using unbounded coin denominations. The 1D DP array dp[i] represents the number of ways to make amount i, initialised with dp[0] = 1. The critical insight is loop order: outer loop over coins, inner loop over amounts. This ensures each combination is counted once, unlike Combination Sum IV where the reversed loop counts permutations. Time O(amount × coins), space O(amount).
Solve LeetCode 286 Walls and Gates by seeding a BFS queue with all gate cells at once and expanding outward. Each room is reached exactly once, giving O(m*n) time with Python and Java implementations.
Master LeetCode 1472 Design Browser History with two clean approaches: an array-and-pointer solution and a doubly linked list alternative, both delivering O(1) per operation.
Master LeetCode 1207 Unique Number of Occurrences by counting value frequencies with Counter, then checking that all frequency counts are distinct using a set — O(n) time and space.
Learn how to delete the middle node of a linked list in one pass using the fast/slow pointer technique with a prev tracker. Covers LeetCode 2095 with Python and Java solutions.
Learn how to solve LeetCode 875 Koko Eating Bananas with binary search on the answer. The eating speed k is monotonic: if k works, any higher speed also works. Binary search over [1, max(piles)] finds the minimum valid k. A feasibility check sums ceil(pile/k) for every pile and verifies the total is at most h hours. Use integer ceiling division (a+b-1)//b to avoid float imprecision. O(n * log(max_pile)) time, O(1) space. Python and Java implementations with canFinish helper included.
Solve LeetCode 310 Minimum Height Trees by peeling away leaf nodes (degree-1) in BFS rounds until 1 or 2 center nodes remain. These centers are the only possible roots that minimize tree height, giving an efficient O(n) solution.
Master LeetCode 215 Kth Largest Element with two key approaches: a min-heap of size k that runs in O(n log k) time and is the safest interview choice, and Quickselect that achieves O(n) average time by partitioning around a pivot. Learn how randomized pivot avoids sorted-input worst cases, when Median of Medians provides a guaranteed O(n) bound, and how Python heapq.nlargest and Java PriorityQueue simplify the heap approach.
Master LeetCode 649 Dota2 Senate with a two-queue greedy approach: maintain separate queues for Radiant and Dire senators indexed by their position, compare queue fronts each round, and let the earlier senator ban the later one — re-entering at index+n for the next round — until one party is eliminated.
Master LeetCode 605 Can Place Flowers with a greedy scan that plants at the first valid gap. Learn the boundary trick, the optimality proof, and why updating the array in-place matters.
Solve LeetCode 1192 Critical Connections using Tarjan's bridge-finding algorithm. Learn how discovery time and low-link values identify bridge edges in O(V+E) with Python and Java implementations.
Learn how to solve LeetCode 1768 Merge Strings Alternately using the two-pointer technique to interleave characters and append remaining characters. Covers Python and Java with O(m+n) time complexity.
Master LeetCode 345 Reverse Vowels of a String with the classic opposite-direction two-pointer pattern. Learn how to skip consonants, handle uppercase vowels with a set, and trace through the full swap sequence in O(n) time.
LeetCode 909 Snakes and Ladders gives you an n x n board numbered 1 to n² in boustrophedon (zigzag bottom-to-top) order. Roll a die 1-6 from each square; if you land on a snake or ladder, teleport to its destination. Find the minimum number of rolls to reach square n², or return -1 if it is unreachable. BFS from square 1 with each roll as an edge and each teleport as a forced redirect gives the shortest path through this unweighted state graph.
Learn how to solve LeetCode 1448 Count Good Nodes in Binary Tree using preorder DFS that tracks the running maximum along each root-to-node path and counts nodes whose value meets or exceeds that maximum.
Maximize the frequency of any element in an array using at most k increments. Sort and apply a sliding window that tracks the cost to bring all window elements up to the rightmost value.
Master LeetCode 151 Reverse Words in a String with the elegant split-reverse-join one-liner in Python and the O(1)-space double-reverse trick in Java. Learn why Python split() without arguments is the ultimate edge-case handler and how the in-place approach impresses interviewers.
Solve LeetCode 1829 Maximum XOR for Each Query by maintaining a running XOR prefix and computing its k-bit complement with a mask to answer every query in O(1) per step.
Learn how to find the maximum depth of a binary tree using recursive DFS, iterative DFS with a stack, and BFS level counting. Understand why the recursive solution is a one-liner, how the stack replaces the call stack in iterative DFS, and how BFS naturally counts levels. Python and Java code included.
Master LeetCode 790 Domino and Tromino Tiling by deriving dp[n] = 2*dp[n-1] + dp[n-3] from first principles: track full-column and partial-column states, collapse them by symmetry, and apply mod 10^9+7 at every step — O(n) time O(1) space iterative solution in Python and Java.
Learn how to solve LeetCode 236 Lowest Common Ancestor of Binary Tree using post-order DFS that finds the split point where both target nodes are first detected across left and right subtrees.
Master LeetCode 91 Decode Ways with a rolling DP approach. Learn why it is a Fibonacci variant with constraints, how zeros kill decode paths, and how to optimize to O(1) space.
Solve LeetCode 198 House Robber with dynamic programming: at each house choose to rob it or skip it, then optimize from O(n) to O(1) space using two rolling variables prev1 and prev2.
Learn how to solve LeetCode 1071 GCD of Strings using the concatenation equality check and Euclid's GCD on string lengths. Covers Python and Java with O(m+n) time complexity.
Master LeetCode 739 Daily Temperatures using a monotonic decreasing stack of indices. For each day, pop all cooler days from the stack and compute their wait time as the index difference. O(n) time and space, each element pushed and popped at most once. Full Python and Java walkthroughs included.
Solve LeetCode 155 Min Stack with push, pop, top, and getMin all in O(1) time. The two-stack approach keeps a parallel minStack whose top always holds the minimum of all elements in the main stack. A tuple variant stores (value, currentMin) pairs on one stack. An advanced constant-space trick encodes the difference between the value and current minimum, recovering the old minimum on pop. All approaches are O(1) per operation; the two-stack method is clearest for interviews.
Master LeetCode 234 Palindrome Linked List with the O(1) space approach that combines three linked list fundamentals: find the middle using fast/slow pointers, reverse the second half in place, and compare both halves node by node. Understand why odd-length lists need no special handling, see clean Python and Java solutions, and learn how this same pattern powers Reorder List and other problems.
Master LeetCode 901 Online Stock Span using a monotonic decreasing stack of (price, span) pairs. For each new price, pop all smaller-or-equal prices and accumulate their spans into a running total. Push (price, total + 1) and return it as the span. O(1) amortized per call, O(n) space total. Full Python and Java walkthroughs included.
Solve LeetCode 2483 Minimum Penalty for a Shop by converting the problem to a sliding penalty scan: start with penalty equal to total Y's, then adjust by -1 for each Y and +1 for each N as you move the closing time right.
Solve LeetCode 2013 Detect Squares by storing point counts in a dict keyed by (x, y). For count(qx, qy), iterate all stored points (px, py) where abs(px-qx) == abs(py-qy) and px != qx — these are diagonal corners. The other two corners are (qx, py) and (px, qy). Multiply counts of all three non-query corners. O(1) add, O(n) count where n = stored points.
Master LeetCode 22 Generate Parentheses with backtracking: track open and close counts, add "(" when open < n and ")" when close < open. All leaves at depth 2n are valid combinations. The count of results equals the nth Catalan number. Includes decision tree walkthrough, DP alternative, and full Python and Java code.
Master LeetCode 268 Missing Number using three approaches: the Gauss sum formula (expected minus actual), XOR cancellation (matching pairs zero out), and sorting with linear scan. Covers Python and Java implementations, overflow considerations, and why XOR is the most elegant O(n) O(1) solution.
Solve LeetCode 2275 Largest Combination with Bitwise AND Greater Than Zero by iterating over each of 24 bit positions, counting candidates with that bit set, and returning the maximum count.
Master LeetCode 309 Buy and Sell Stock with Cooldown using a three-state DP machine. Learn how hold, sold, and rest states model the mandatory cooldown, why two states break down, and how to trace through a walk-through example to the O(n) O(1) solution.
Master LeetCode 79 Word Search with DFS backtracking that marks cells visited in-place using a sentinel character. Understand the four-directional recursion, in-place visited marking to save O(mn) space, and powerful pruning tricks like reversing the word when the last character is rarer than the first. See clean Python and Java solutions with full complexity analysis.
Master LeetCode 237 Delete Node in a Linked List with the copy-next-value trick. Learn why head access is not needed: overwrite the target node's value with its successor's value, then bypass the successor. Includes a full walk-through on a 4-node list, Python and Java two-line solutions, O(1) time and space analysis, and key interview notes about the tail constraint.
Master LeetCode 727 Minimum Window Subsequence with the efficient forward-backward two-pointer technique: scan forward through S1 matching all characters of S2, then scan backward from the match end to find the earliest valid start, yielding the minimum window. Understand why the backward pass must match S2 in reverse order, see Python and Java implementations with full trace examples, and learn how this problem connects to Minimum Window Substring, Is Subsequence, and the broader window-subsequence family.
Solve LeetCode 1647 with a greedy frequency-counting strategy: sort frequencies descending, use a set to track used values, and decrement duplicates until each frequency is unique.
Solve LeetCode 322 Coin Change with bottom-up DP where dp[i] stores the minimum coins needed for amount i. Treat the problem as unbounded knapsack, see why greedy fails with a concrete counterexample, and explore BFS as a clean alternative that models each amount as a graph node.
Master LeetCode 542 01 Matrix with multi-source BFS. Learn to enqueue all zero cells simultaneously, expand outward level by level, and compute the distance to the nearest zero for every cell in O(m*n) time.
LeetCode 409 asks for the length of the longest palindrome buildable from a string of characters. The key insight: even-count characters contribute fully, odd-count characters contribute count-1, and you can add one center character if any odd frequency exists.
Master LeetCode 24 Swap Nodes in Pairs with two clean approaches: an iterative dummy-node solution using a prev pointer to rewire each pair in three steps with O(1) space, and a recursive solution that handles one pair at a time and delegates the rest. Understand why the dummy node makes the first pair no different from any other, see Python and Java code with full pointer-state traces, and learn how this problem connects to Reverse k-Group and other linked list swapping patterns.
Master LeetCode 1845 Seat Reservation Manager using a min-heap. Reserve returns the smallest available seat via heappop; unreserve pushes the seat back. Both operations run in O(log n) time.
LeetCode 1189 asks how many times you can form the word "balloon" using characters from a given string. The key insight: count frequencies of b, a, l, o, n in the text, then divide l and o counts by 2 since they appear twice in "balloon". The minimum ratio is your answer.
Master LeetCode 337 House Robber III with post-order DFS. Return a (rob, skip) pair from each subtree to apply tree DP in O(n) time and maximize loot on a binary tree.
LeetCode 200 Number of Islands asks you to count connected land components in a binary grid. DFS flood fill is the simplest approach: iterate all cells, and when a land cell is found, increment the count and sink the entire island. BFS and Union-Find are powerful alternatives. This deep dive covers all three methods with full complexity analysis and pitfalls.
LeetCode 714 asks you to maximize profit from unlimited stock trades where each sell incurs a transaction fee. The DP state machine maintains two states — cash (not holding) and hold (holding stock) — and updates them each day in O(1) space with a single O(n) pass. The fee is subtracted on sell, naturally preventing churning on tiny gains.
Master LeetCode 1679 Max Number of K-Sum Pairs using hashmap complement counting for O(n) time: track frequencies, pair each element with its complement k minus num, and count the maximum number of removal operations possible.
LeetCode 8 String to Integer atoi asks you to parse a string and convert it to a 32-bit signed integer, replicating the behavior of C's atoi function. The algorithm proceeds in four steps: skip leading whitespace, read an optional + or - sign, accumulate consecutive digit characters into an integer, then clamp the result to the 32-bit signed range [-2147483648, 2147483647]. A formal DFA with states START, SIGNED, IN_NUMBER, and END models the transitions cleanly. This deep dive covers the sequential parsing approach, overflow detection before multiplication, the state machine alternative, Python and Java implementations, and connections to related string parsing problems.
Master LeetCode 334 Increasing Triplet Subsequence with the two-variable greedy approach. Learn how tracking first and second minimum values lets you detect a length-3 increasing subsequence in O(n) time and O(1) space, and understand why updating first does not invalidate second.
Master LeetCode 53 Maximum Subarray with Kadane's algorithm as dynamic programming: dp[i] = max(nums[i], dp[i-1] + nums[i]) compressed to one variable. Covers the divide-and-conquer O(n log n) follow-up, the buy/sell stock equivalence via daily gains, and full Python and Java code for both approaches.
Solve LeetCode 189 Rotate Array with three approaches — extra array, cyclic replacement, and the triple reversal trick. The reversal method is O(n) time O(1) space and the go-to interview answer.
Solve LeetCode 1110 Delete Nodes and Return Forest with post-order DFS. Delete target nodes bottom-up, and any orphaned children automatically become new roots of the resulting forest.
Solve LeetCode 59 Spiral Matrix II by initializing an n x n zero matrix and maintaining four boundaries: top, bottom, left, right. Fill top row left to right, right column top to bottom, bottom row right to left, left column bottom to top — then shrink each boundary. Repeat while top <= bottom and left <= right. Counter increments from 1 to n^2. O(n^2) time, O(1) extra space.
Master LeetCode 1456 Maximum Number of Vowels in a Substring of Given Length with a fixed-size sliding window. Learn to count vowels in O(n) time and O(1) space by adding the incoming right character and subtracting the outgoing left character on each slide. Includes a vowel set for O(1) lookup, a full walk-through example, and Python and Java code with an early-exit optimization.
LeetCode 2381 Shifting Letters II gives you a string and an array of shift operations, each covering a range [l, r] with a direction — forward or backward. Applying each shift naively to every character in its range is O(n × q) and too slow. The difference array technique brings this to O(n + q): mark the boundaries of each shift, compute a prefix sum to get the net shift at each position, then apply mod 26 to produce the final character.
Master LeetCode 269 Alien Dictionary with complete edge case handling, BFS Kahn's algorithm, DFS three-state coloring, and cycle detection proof. Includes Python and Java code with O(C) time analysis.
LeetCode 2559 gives you an array of strings and a list of queries [l, r]. For each query, count how many strings in the range start AND end with a vowel. The optimal approach precomputes a boolean array — 1 if word starts and ends with a vowel, 0 otherwise — builds a prefix sum over it, then answers every query in O(1) with prefix[r+1] - prefix[l]. This classic prefix sum pattern turns O(q*n) brute force into O(n + q).
Count nodes in a complete binary tree in O(log^2 n) by comparing left and right subtree heights. When heights match, the left subtree is perfect and contributes 2^h - 1 nodes instantly — no full traversal needed.
Learn how to solve LeetCode 6 Zigzag Conversion by assigning each character to its row using a direction toggle and then concatenating all rows for the final output.
Master LeetCode 543 Diameter of Binary Tree with post-order DFS that computes height while updating a global maximum. Understand why diameter does not have to pass through root, how height and diameter serve different roles, and see Python and Java solutions with O(n) time complexity.
Master LeetCode 643 Maximum Average Subarray I with the fixed-size sliding window technique. Learn how to maintain a running sum, avoid repeated division, and solve it in O(n) time with O(1) space.
Master LeetCode 1161 Maximum Level Sum of a Binary Tree with BFS level-order traversal. Learn how to sum each level, handle negative values correctly, and return the smallest level with the maximum sum in O(n) time.
Master LeetCode 450 Delete Node in a BST with a clean recursive solution. Learn the three deletion cases: leaf removal, single-child bypass, and two-child inorder successor replacement, each handled in O(h) time.
LeetCode 1431 asks which kids could have the greatest candies after receiving extra ones. The trick: find the max first, then compare each kid's total against it.
Solve LeetCode 1822 Sign of the Product of an Array by counting negatives instead of computing the actual product. Even count means positive, odd means negative, any zero means zero.
Master LeetCode 1004 Max Consecutive Ones III with the variable sliding window technique. Learn how tracking zero count inside the window — expanding right and shrinking left when zeros exceed k — finds the longest all-ones subarray with at most k flips in O(n) time and O(1) space.
Master LeetCode 380 Insert Delete GetRandom O(1) by combining a HashMap and array with swap-to-back deletion. All three operations run in O(1) average time.
LeetCode 2244 asks for the minimum rounds to complete all tasks where each round handles 2 or 3 tasks of the same difficulty. The key insight: any frequency >= 2 decomposes into groups of 2 and 3, making ceil(freq/3) the elegant per-level answer.
LeetCode 232 Implement Queue Using Stacks asks you to implement a FIFO queue using only two LIFO stacks. The inbox stack receives all pushes; when a pop or peek is needed and the outbox is empty, all inbox elements transfer to outbox — reversing their order and restoring FIFO semantics. Each element transfers at most once, giving O(1) amortized cost for all operations.
LeetCode 994 Rotting Oranges asks how many minutes until no fresh orange remains, or -1 if impossible. Multi-source BFS treats all initially rotten cells as simultaneous starting points, processing one level per minute. This deep dive covers the setup, level counting, every edge case, and the DFS-vs-BFS decision in full detail.
LeetCode 72 Edit Distance asks for the minimum number of insert, delete, and replace operations to convert word1 into word2. Solve it with a 2D DP table where dp[i][j] captures the optimal cost for every prefix pair, space-optimize to O(n) with a rolling row, and learn how edit distance connects to LCS and the Levenshtein distance used in real-world tools.
LeetCode 169 Majority Element asks you to find the element that appears more than n/2 times in an array. The Boyer-Moore Voting Algorithm is the optimal solution: maintain a candidate and a vote count, incrementing for matches and decrementing for mismatches. Because the majority element appears more than all others combined, it always wins the "battle royale" and survives. This deep dive covers Boyer-Moore in detail, sorting, hashmap, and divide-and-conquer alternatives, plus a full walk-through example.
Master LeetCode 2864 Maximum Odd Binary Number with a greedy one-pass approach. Count 1s, place all but one at the front for maximum value, fill zeros in the middle, and append a single 1 at the end to guarantee oddness. O(n) time and O(n) space.
LeetCode 62 Unique Paths counts the number of distinct paths a robot can take from the top-left to the bottom-right of an m x n grid moving only right or down. Solve it with 2D DP in O(m*n) space, optimize to O(n) with a 1D rolling array, or reduce to a single combination formula C(m+n-2, m-1) for true O(1) space.
Solve LeetCode 1704 Determine If String Halves Are Alike by splitting the string at its midpoint, counting vowels in each half using a set lookup, and returning whether the two counts are equal.
Master LeetCode 73 Set Matrix Zeroes with the O(1) space trick: use matrix[i][0] to flag row i and matrix[0][j] to flag column j. A separate boolean tracks the first column since matrix[0][0] serves double duty. Two passes handle marking and zeroing. Zero the first row and column last to avoid corrupting your own markers.
Master LeetCode 560 Subarray Sum Equals K with the prefix sum plus hashmap pattern that runs in O(n) time and O(n) space. Learn why the classic sliding window approach breaks down when the array contains negative numbers, trace through the prefix sum insight step by step, and see clean Python and Java implementations that count all valid subarrays in a single pass.
Master LeetCode 128 Longest Consecutive Sequence with the HashSet and sequence-start approach. Insert all numbers into a set for O(1) lookup, then for each number check if num-1 is absent — if so, it is a sequence start. Count forward from there. Each number is visited at most twice across all sequences, making the total work O(n) even though the code has nested loops. Also covers the sorting fallback, Union-Find alternative, and Python/Java implementations.
LeetCode 394 Decode String encodes repetition as k[encoded_string] and asks you to decode fully, handling arbitrary nesting. The stack-based solution maintains a current string and current number, pushing both onto the stack at each opening bracket and resetting them, then at each closing bracket popping the saved pair and producing prevString + currentString * count. This cleanly handles arbitrary nesting because each bracket level has its own saved context on the stack. Multi-digit repeat counts are accumulated digit by digit using num = num*10 + digit before the bracket is encountered.
Master LeetCode 191 Number of 1 Bits with three approaches: the 32-iteration loop-and-check with n & 1 and right shift, Brian Kernighan's O(k) trick using n & (n-1) to clear the lowest set bit, and built-in popcount functions. Covers the Java unsigned right shift warning, why n & (n-1) works, and all Python and Java code.
LeetCode 112 Path Sum asks whether a root-to-leaf path exists where node values sum to a target. The cleanest approach uses DFS with subtraction: at each node subtract its value from the target, and at a leaf check if the remaining value is zero. This avoids carrying a running sum and keeps the recursion minimal.
Master LeetCode 1143 Longest Common Subsequence with a complete 2D DP table walkthrough, space optimization to O(min(m,n)), LCS string recovery by backtracking, and its connection to edit distance and Unix diff.
LeetCode 2130 Maximum Twin Sum of a Linked List asks for the largest sum of node i and its twin node (n-1-i) in an even-length linked list. The optimal O(n) time O(1) space approach uses the palindrome linked list pattern: find the middle with fast/slow pointers, reverse the second half iteratively, then traverse both halves together summing twin pairs and tracking the maximum.
Learn how to solve LeetCode 12 Integer to Roman using a greedy algorithm with a 13-entry value-symbol table. By including subtractive pairs like CM and IV directly in the table, the algorithm handles all Roman numeral edge cases without any conditionals.
Solve LeetCode 114 Flatten Binary Tree to Linked List using three approaches: recursive reverse postorder with a prev pointer, iterative with a stack, and Morris traversal in O(1) space. All three produce the correct preorder-ordered linked list using only right pointers.
Solve LeetCode 124 Binary Tree Maximum Path Sum by separating two concepts: the gain a node contributes upward (single branch) and the max path through the node (both branches). Post-order DFS with a global max variable handles negative subtrees cleanly by treating them as zero gain.
LeetCode 39 Combination Sum is solved with backtracking — pick a candidate, subtract it from the remaining target, and recurse from the same index to allow unlimited reuse. Sort candidates first so you can break early when a candidate exceeds the remaining target, pruning entire subtrees in one check.
LeetCode 90 Subsets II extends Subsets I by handling duplicate elements. Sort the array first, then in the backtracking loop skip any element equal to its predecessor when we are not at the start of the current level. This one condition — i > start AND nums[i] == nums[i-1] — eliminates all duplicate subsets and generates the unique power set.
Master LeetCode 33 Search in Rotated Sorted Array with a single modified binary search pass: determine which half is sorted, check if target is in that range, then narrow accordingly — all in O(log n) time.
Master LeetCode 25 Reverse Nodes in k-Group. Learn to count k nodes ahead, reverse each segment iteratively, and reconnect the groups in O(n) time and O(1) space.
Master LeetCode 986 Interval List Intersections with a two-pointer approach: compute the overlap of A[i] and B[j] using max(start) and min(end), then advance whichever pointer ends sooner for an O(m+n) solution across both sorted interval lists.
LeetCode 84 asks you to find the largest rectangle that can be formed inside a histogram defined by an array of bar heights. The brute-force O(n^2) approach expands left and right from every bar, but the optimal O(n) solution uses a monotonic increasing stack of indices. When a bar shorter than the stack top is encountered, bars are popped and their maximum area is calculated using the popped height and a width derived from the current index and the new stack top. Appending a sentinel bar of height 0 flushes all remaining bars at the end, eliminating a separate post-loop pass.
Master LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal using preorder root identification, inorder left/right splitting, and a hashmap for O(1) index lookup. O(n) time and space. Full Python and Java implementations with index-pointer technique.
Solve LeetCode 399 Evaluate Division by building a weighted directed graph where variables are nodes and ratios are edge weights. Use DFS path multiplication to evaluate ratio queries — with Python and Java implementations plus a Union-Find with weights alternative.
Learn to solve LeetCode 746 Min Cost Climbing Stairs with bottom-up DP and O(1) space. Roll two variables instead of a full array, then take min of the last two values to reach the top.
Master LeetCode 153 Find Minimum in Rotated Sorted Array. Learn why comparing mid to the right endpoint — not the left — correctly identifies the unsorted half containing the minimum, with clean Python and Java implementations in O(log n).
Master LeetCode 787 Cheapest Flights Within K Stops using modified Bellman-Ford with k+1 rounds or BFS with pruning. Full walkthrough with the critical copy trick, Python and Java code.
Master LeetCode 150 Evaluate Reverse Polish Notation using stack-based postfix evaluation. Push numbers onto a stack; for each operator pop two operands, compute the result (b then a for order-sensitive ops), and push it back. Handle Python division truncation with int(a/b). O(n) time, O(n) space. Full Python and Java walkthroughs included.
Master LeetCode 121 Best Time to Buy and Sell Stock with the one-pass greedy approach: track the running minimum price and compute max profit at each step. Covers brute force O(n^2), the greedy O(n) single-pass solution, Kadane's algorithm connection via daily gains, why greedy works, and full Python and Java code.
Master LeetCode 103 Zigzag Level Order Traversal with BFS and a direction flag: collect each level with a queue, toggle leftToRight after each level, reverse odd levels before adding to the result. O(n) time and space. Deque-based and DFS alternatives also covered.
Solve LeetCode 1851 Minimum Interval to Include Each Query by sorting intervals by start time, sorting queries while retaining original indices, and sweeping with a min-heap of (size, end) pairs — adding qualifying intervals and lazily popping expired ones so the heap top is always the smallest covering interval.
Solve LeetCode 528 Random Pick with Weight by building a prefix sum array in O(n) and using binary search in O(log n) per pick. A random number in [1, totalSum] maps to exactly one weight range, giving each index the correct probability proportional to its weight.
Master LeetCode 2215 Find the Difference of Two Arrays by converting inputs to sets, then using bidirectional set subtraction to produce two lists of unique elements not shared between the arrays — O(n+m) time.
Master LeetCode 110 Balanced Binary Tree with a post-order DFS helper that returns the actual height when balanced or -1 when unbalanced. Understand why the naive O(n²) solution recomputes heights needlessly, how the -1 sentinel propagates to short-circuit further recursion, and see clean Python and Java solutions in O(n) time.
Master LeetCode 662 Maximum Width of Binary Tree with BFS heap-style indexing, index overflow normalization, and a DFS alternative. Includes Python and Java solutions with O(n) time and O(w) space analysis.
Solve LeetCode 66 Plus One by iterating a digit array from right to left. When a digit is less than 9, increment it and return immediately. When a digit is 9, set it to 0 and carry left. If carry propagates past all digits — the all-9s case — prepend 1 to create a new leading digit. O(n) time, O(1) space for most inputs.
Solve LeetCode 735 Asteroid Collision using a stack-based simulation. Iterate through the asteroid array; when a negative asteroid meets a positive stack top, compare absolute sizes. Pop the stack top if the current is larger, discard current if smaller, pop both if equal. Non-colliding pairs — two positives, two negatives, or negative before positive — are pushed directly. O(n) time, O(n) space.
Master LeetCode 443 String Compression with the two-pointer in-place run-length encoding approach. Learn how to count consecutive character runs, write the character and its count digits back into the array without extra space, and handle the tricky single-character and multi-digit count edge cases in Python and Java.
Master LeetCode 1493 Longest Subarray of 1s After Deleting One Element with sliding window. Learn why the answer is right-left (not right-left+1), how the mandatory deletion shapes the formula, and how to handle the all-1s edge case cleanly in O(n) time.
LeetCode 2300 asks for the count of valid spell-potion pairs where spell * potion >= success. The optimal approach sorts potions once and then binary searches for the minimum valid potion per spell using ceiling division. This drops runtime from O(n*m) to O((n+m) log m).
LeetCode 283 Move Zeroes asks you to move all zeros in an array to the end while maintaining the relative order of non-zero elements, in-place without extra space. The two-pointer partition is the optimal solution: a slow pointer tracks the next position for a non-zero element while a fast pointer scans ahead. Each time the fast pointer finds a non-zero value, it swaps with the slow pointer and both advance. Zeros naturally pile up at the end like a snowball growing as the fast pointer sweeps through. This deep dive covers the swap approach, the optimal-writes overwrite variant, the snowball analogy, Python and Java code, and connections to related partition problems.
LeetCode 162 Find Peak Element asks for any index where the value is strictly greater than its neighbors. Binary search on the comparison between nums[mid] and nums[mid+1] eliminates half the array each iteration, delivering an O(log n) solution in O(1) space.
LeetCode 21 Merge Two Sorted Lists asks you to splice two sorted linked lists into one sorted list. The iterative dummy-node approach runs in O(m+n) time and O(1) space; the recursive approach matches time complexity but uses O(m+n) call stack space. Both strategies extend directly to harder merge problems.
Master LeetCode 1466 Reorder Routes to Make All Paths Lead to the City Zero. Learn the DFS/BFS trick of building an undirected graph with direction markers and counting outgoing edges in one pass.
LeetCode 2914 asks for the minimum changes to make a binary string beautiful, defined as splittable into even-length substrings of all-0s or all-1s. The key insight is to partition the string into consecutive pairs at indices (0,1), (2,3), (4,5), and so on. Each pair that has mismatched characters needs exactly one flip. Count the mismatched pairs and return that count — a clean O(n) greedy solution.
LeetCode 1408 String Matching in an Array asks you to find all strings in the array that appear as a substring of at least one other string in the same array. With n up to 100 and string lengths up to 30, a brute force O(n^2 * m) nested loop is perfectly efficient. For each string, iterate over all others, skip the same index, and check if it is contained using the built-in substring operator.
Learn how to solve LeetCode 1963 Minimum Number of Swaps to Make the String Balanced by cancelling matched bracket pairs in a single pass and computing ceil(unmatched / 2) for the answer. The key insight is that after natural matches are removed, every swap of "][" into "[]" simultaneously fixes two unmatched brackets.
Minimize the number of boats to rescue everyone given each boat carries at most 2 people within a weight limit. Sort the array, then apply a two-pointer greedy strategy pairing the heaviest with the lightest person on each pass.
Master LeetCode 5 Longest Palindromic Substring with expand-around-center: for each index try both odd and even length expansions, track the longest palindrome found, and achieve O(n^2) time with O(1) space — the cleanest interview solution. Manacher's O(n) algorithm is also covered.
Master LeetCode 424 Longest Repeating Character Replacement with a variable sliding window, a 26-slot frequency array, and the key maxFreq optimization that avoids O(26) rescanning on every shrink. Understand why the window only grows when a new maximum frequency is found, making this an elegant O(n) time, O(1) space solution.
LeetCode 7 Reverse Integer asks you to reverse the digits of a 32-bit signed integer and return 0 if the result overflows the range [-2^31, 2^31-1]. The key technique is the pop-and-push loop: pop the last digit with x % 10, remove it with integer division, push it onto the reversed result with result * 10 + digit. The critical detail is checking for 32-bit overflow before the push — not after — to avoid undefined behavior in C/C++ and silent wrapping in Java. Python requires manual clamping since its integers have infinite precision.
LeetCode 160 Intersection of Two Linked Lists asks you to find the node where two singly linked lists merge. The optimal O(m+n) time O(1) space solution uses the two-pointer switch trick: pointer A starts at headA and pointer B starts at headB; when either reaches null it switches to the other list's head. After at most m+n steps both pointers land on the intersection node — or both reach null if no intersection exists.
Master LeetCode 242 Valid Anagram with two approaches: O(n log n) sorting and O(n) frequency counting. Covers the int[26] array trick for lowercase, HashMap for the Unicode follow-up, the single-counter optimization, and full Python and Java implementations with early-exit length check.
LeetCode 51 N-Queens is solved with backtracking — place one queen per row, prune invalid columns and diagonals immediately using three sets. The diagonal trick compresses 2D threat detection into O(1) set lookups using row-col and row+col as identifiers.
LeetCode 2 Add Two Numbers gives you two reverse-order linked lists of digits and asks you to return their sum as a linked list in the same reverse-order format. The key insight is that reverse storage is a gift — least significant digits come first, matching natural addition order. Iterate both lists with a carry variable, produce each result digit with sum % 10 and carry = sum / 10, and use a dummy head node to avoid special-casing the first node. After both lists are exhausted, check for a remaining carry. The algorithm runs in O(max(m,n)) time and O(max(m,n)) space.
LeetCode 378 Kth Smallest Element in a Sorted Matrix gives you an n x n matrix where every row and every column is sorted in ascending order. The challenge is to find the kth smallest element overall without fully sorting the matrix. Two fundamentally different strategies solve this: a min-heap that merges the rows like sorted lists and stops at the kth pop, and a binary search on the value range that counts elements beneath a midpoint using a clever staircase traversal from the bottom-left corner. Knowing which to use — and why the binary search answer is guaranteed to exist in the matrix — is what distinguishes a polished solution.
Solve LeetCode 238 Product of Array Except Self in O(n) time and O(1) extra space. Learn why division fails with zeros, and how prefix and suffix products stored directly in the output array give a clean, interview-ready solution.
Master LeetCode 452 Minimum Number of Arrows to Burst Balloons with a greedy interval approach: sort by xend, shoot at the first balloon's end, skip all overlapping balloons, and repeat — achieving O(n log n) time and O(1) space with a clean single-pass algorithm.
Learn how to solve LeetCode 226 Invert Binary Tree three ways: recursive swap in 4 lines, iterative BFS with a queue, and iterative DFS with a stack. Understand the famous Homebrew interview meme and why this problem is a great teaching tool for tree recursion.
Solve LeetCode 152 Maximum Product Subarray by tracking both curMax and curMin at each element. When a negative number is encountered, swap them — because multiplying by a negative flips the sign, making the previous minimum the new maximum candidate.
Master LeetCode 338 Counting Bits using three O(n) dynamic programming approaches: the right-shift recurrence dp[i] = dp[i >> 1] + (i & 1), Brian Kernighan's recurrence dp[i] = dp[i & (i-1)] + 1, and the last-set-bit recurrence dp[i] = dp[i - (i & -i)] + 1. Covers why each recurrence is correct, how each step reuses previously computed results, Python and Java implementations, and the connection to LeetCode 191 Number of 1 Bits.
Master LeetCode 392 Is Subsequence with the two-pointer greedy technique. Learn how advancing i on s and j on t — matching characters one by one — solves the basic case in O(|s|+|t|) time, and how the follow-up binary search preprocessing makes k queries efficient at O(|t| + k*|s|*log|t|).
Master LeetCode 2870 Minimum Number of Operations to Make Array Empty. Learn how frequency counting and ceiling division by 3 yields the minimum operations, why frequency 1 is the only impossible case, and how this mirrors LeetCode 2244 Minimum Rounds to Complete Tasks.
Master LeetCode 303 Range Sum Query Immutable with a prefix sum array. Learn how to precompute cumulative sums in O(n) during initialization and answer every range query in O(1) using prefix[right+1] - prefix[left]. Includes the 1-indexed prefix trick, a full walk-through example, and Python and Java code.
LeetCode 235 Lowest Common Ancestor of a BST uses the BST ordering property to find the LCA in O(h) time and O(1) space. By comparing both node values against the current node, you navigate left or right until you find the split point — the deepest node where p and q land on different sides.
Learn how to solve LeetCode 767 Reorganize String using a max-heap greedy algorithm that places the most frequent character first and holds the previous character to avoid adjacency, achieving O(n log 26) time.
LeetCode 3043 asks for the length of the longest common prefix shared between any integer in arr1 and any integer in arr2, where prefix means leading digits. The canonical solution builds a trie from arr1 digit by digit, then queries each number from arr2 through the trie, advancing one digit at a time and stopping on a mismatch. A HashSet-of-all-prefixes alternative is simpler to code but uses more memory.
Learn how to solve LeetCode 118 Pascal's Triangle by constructing each row from the previous one. Every interior element equals the sum of two values above it, and each row maps directly to combinatorial coefficients C(n,k) — making this problem a gateway to combinatorics and dynamic programming.
Learn how to solve LeetCode 885 Spiral Matrix III by simulating a clockwise spiral walk that starts at (rStart, cStart) and expands outward. The key insight is that step count increases by 1 after every two direction changes, and out-of-bounds positions are simply skipped until all R*C valid cells are collected.
Master LeetCode 703 Kth Largest Element in a Stream with a min-heap of size k. The heap top is always the kth largest. Constructor runs O(n log k) to initialize, each add call runs O(log k). Covers Python heapq and Java PriorityQueue implementations with a full walk-through example.
Master LeetCode 70 Climbing Stairs by recognizing the Fibonacci pattern. Learn top-down memoization, bottom-up DP, O(1) rolling variables, and the matrix exponentiation bonus for O(log n) time.
LeetCode 323 Number of Connected Components asks you to count the distinct connectivity groups in an undirected graph given n nodes (0 to n-1) and a list of edges. The two canonical approaches are DFS/BFS — iterate unvisited nodes, flood-fill each component, and count — and Union-Find, which maintains a parent array, unions nodes sharing an edge, and tracks the running component count by decrementing on each successful union. Union-Find with path compression and union by rank runs in amortized O(alpha(n)) per operation, making it extremely efficient for large sparse graphs and a natural fit when edges arrive dynamically.
Solve LeetCode 1318 Minimum Flips to Make a OR b Equal to c by examining each bit position independently. When the target c bit is 0 and both a and b have 1s, you must flip both — costing 2. When the target c bit is 1 and both a and b are 0, one flip suffices. Sum these per-bit costs across all 32 positions for the answer.
Master LeetCode 347 Top K Frequent Elements with three distinct approaches. Start by counting frequencies with a hashmap in O(n), then select the top k using a min-heap (O(n log k)), bucket sort (O(n) guaranteed), or quickselect (O(n) average). Learn the bucket sort trick, why it achieves linear time, and how Python's Counter.most_common(k) is a built-in shortcut for this exact pattern.
Solve LeetCode 417 Pacific Atlantic Water Flow by running reverse BFS or DFS from each ocean border uphill into the grid. The intersection of Pacific-reachable and Atlantic-reachable cells is the answer — with Python and Java implementations at O(m*n) time.
Master LeetCode 622 Design Circular Queue with an array-based ring buffer: allocate a fixed array of size k, track front and rear pointers, use rear = (rear + 1) % k to wrap around, and maintain a count to detect empty and full states — all six operations run in O(1) time.
Master LeetCode 724 Find Pivot Index with a single-pass prefix sum approach. Learn how to compute the total sum once and check left-right balance at every index in O(n) time and O(1) space. Includes the 2*leftSum + nums[i] == totalSum formulation, a full walk-through example, and Python and Java code.
Learn how to solve LeetCode 566 Reshape the Matrix by mapping 2D indices to a single linear index and back. The divmod trick converts any (i, j) in the original matrix to (newRow, newCol) in the reshaped matrix in one pass without extra flattening.
LeetCode 140 Word Break II asks for all valid sentences formed by inserting spaces into string s, where every word is in the dictionary. The key insight is that DP from Word Break I only proves feasibility but cannot reconstruct paths. Use backtracking to try each valid prefix, recurse on the suffix, and memoize results keyed by start index to avoid exponential re-exploration of repeated suffixes.
Learn how to determine if one binary tree is a subtree of another by checking isSameTree at every node of the main tree. Understand why O(m*n) is the theoretical worst case but short-circuits in practice, and explore the serialization approach that achieves O(m+n) time using substring matching. Python and Java code included.
Learn how to determine if a binary tree is a valid BST using three approaches. The min/max bounds method passes inherited constraints downward through every recursive call, avoiding the classic mistake of only checking immediate children. Inorder traversal exploits the fact that a valid BST produces a strictly increasing sequence. Morris traversal threads the tree to achieve O(n) time with O(1) space. Python and Java code included.
Solve LeetCode 202 Happy Number by repeatedly summing the squares of a number's digits. Use a HashSet to detect cycles in O(log n) space or apply Floyd's tortoise-and-hare algorithm in O(1) space. The mathematical insight: every sequence is bounded and must either reach 1 or enter a cycle — and those cases are distinguishable.
Master LeetCode 101 Symmetric Tree with recursive mirror comparison or iterative BFS. Learn the cross-children insight that makes symmetry checking intuitive and efficient.
Master LeetCode 190 Reverse Bits with the bit-by-bit approach (extract with n & 1, place with left shift and OR, repeat 32 times) and the divide-and-conquer bit-mask method that reverses in 5 swap operations. Covers the Python 32-bit mask caveat, the Java unsigned right shift, caching for multiple calls, and full Python and Java code.
Master LeetCode 111 Minimum Depth of Binary Tree with BFS for guaranteed early termination at the first leaf, or DFS with correct single-child node handling to avoid the classic null-branch pitfall.
LeetCode 141 Linked List Cycle asks whether a linked list contains a cycle — a node whose next pointer points back to a previous node. Floyd's fast and slow pointer algorithm solves this in O(n) time and O(1) space: move slow one step and fast two steps; if they ever meet, a cycle exists. The HashSet approach is simpler but uses O(n) extra space.
Master LeetCode 559 Maximum Depth of N-ary Tree using recursive DFS and BFS level counting. Learn how the binary tree depth pattern extends naturally to nodes with any number of children.
Master LeetCode 621 Task Scheduler with the (maxFreq-1)*(n+1)+countOfMaxFreq formula and greedy max-heap simulation. Understand idle slots, cooldown gaps, and when the formula gives the same answer as total tasks.
LeetCode 2390 Removing Stars from a String asks you to process a string where each star removes the closest non-star character to its left and return the resulting string after all stars are resolved. The stack solution is elegant: iterate left to right, pushing non-star characters and popping on each star. This is identical to simulating a backspace key — non-star characters are keystrokes and stars are backspaces. The stack naturally tracks what remains after every deletion, and joining it at the end gives the final result in O(n) time and O(n) space.
Master LeetCode 40 Combination Sum II with sorted backtracking. Learn the exact skip condition that eliminates duplicate combinations without reusing elements.
Master LeetCode 1 Two Sum with the single-pass hashmap complement lookup: for each number compute target minus num and check the map, then store num to its index. Covers brute force O(n^2) vs hashmap O(n), why sorting loses indices, one-pass vs two-pass, and full Python and Java code with interview tips.
Master LeetCode 2034 Stock Price Fluctuation by combining a HashMap for timestamp-to-price lookups with two heaps and lazy deletion — so corrections to past prices never break your max/min queries.
Solve LeetCode 43 Multiply Strings by simulating grade-school multiplication digit by digit. For each pair of digits at indices i and j, accumulate the product into a result array at positions i+j+1, then process carries in a single right-to-left pass. Strip leading zeros and join digits into the result string. O(m*n) time, O(m+n) space.
Master LeetCode 50 Pow(x, n) with binary exponentiation: square the base and halve the exponent each step, reducing O(n) to O(log n). For odd n, multiply the current result by x before halving. Negative n is handled by computing pow(1/x, -n). The iterative version processes each bit of n, contributing x^(2^position) to the result. Java requires casting n to long before negating to avoid Integer.MIN_VALUE overflow.
Master LeetCode 1372 Longest ZigZag Path in a Binary Tree with a single-pass DFS using two counters per node. Learn how alternating left-right direction tracking and resetting to 0 on same-direction continuation captures every possible zigzag path in O(n) time.
Solve LeetCode 1804 Implement Trie II by augmenting each TrieNode with two counters: countPrefix (incremented for every word that passes through the node) and countWord (incremented when a word ends at the node). These counters directly answer both count queries in O(m) time and support erase by decrementing along the same path.
Solve LeetCode 1732 Find the Highest Altitude by accumulating gains into a running prefix sum and tracking the maximum. The starting altitude 0 is always a candidate.
Solve LeetCode 896 Monotonic Array by tracking two boolean flags in one pass. If either isIncreasing or isDecreasing survives to the end, the array is monotone.
Solve LeetCode 846 Hand of Straights in O(n log n) with a sorted counter greedy. Start every group from the smallest available card and check that the next groupSize consecutive values are present in sufficient quantity.
Master LeetCode 252 Meeting Rooms with a simple sort-and-scan approach. Sort all intervals by start time, then check each consecutive pair: if intervals[i].start < intervals[i-1].end, return false. Otherwise return true. O(n log n) time, O(1) space — handles empty lists, single meetings, and shared endpoints.
LeetCode 1926 Nearest Exit from Entrance in Maze gives you an m x n grid of plus signs (walls) and dots (empty cells) and an entrance coordinate. You must return the minimum number of steps to reach any boundary empty cell that is not the entrance, or -1 if none exists. BFS from the entrance explores the grid level by level, and the first boundary cell reached (excluding the entrance) is the nearest exit. Mark cells visited by setting them to plus to avoid revisits. Time complexity is O(m*n) with O(m*n) space.
Master LeetCode 1123 LCA of Deepest Leaves with post-order DFS. Learn to track subtree depths recursively and find the ancestor where both sides reach maximum depth, solving the problem in O(n) time with O(h) space.
Learn how to solve LeetCode 209 Minimum Size Subarray Sum with a variable sliding window that expands to satisfy the sum constraint and shrinks to optimize the length, achieving O(n) time.
Learn how to solve LeetCode 179 Largest Number by defining a custom comparator that compares string concatenations a+b vs b+a, sorting the array in that order, and joining the result.
Master LeetCode 4 Median of Two Sorted Arrays with the optimal binary search partition technique. Learn how to split both arrays such that all elements on the left side are less than or equal to all elements on the right side, how to binary search on the shorter array to keep the search space minimal, and how to handle edge cases with negative and positive infinity sentinels for clean, correct median computation in O(log min(m,n)) time.
Master LeetCode 1091 Shortest Path in Binary Matrix by applying BFS with 8-directional movement. Learn why BFS is provably optimal for shortest paths in unweighted graphs, how to handle the diagonal directions that make this problem distinct from standard 4-direction grid BFS, and the critical edge cases around grid[0][0] and grid[n-1][n-1] that must be checked before starting the traversal.
Master LeetCode 778 Swim in Rising Water by understanding that you want the path where the maximum elevation is minimized — a classic minimax path problem. Learn the Dijkstra-like min-heap approach that greedily expands the lowest-cost cell and reaches (n-1,n-1) with the optimal answer, as well as the binary search plus BFS alternative that checks whether a valid path exists for each candidate time threshold.
Master LeetCode 218 The Skyline Problem by learning the line sweep technique that creates start and end events at every building edge, uses a max-heap to track active heights, and records a key point whenever the maximum height changes. Understand how to handle ties at the same x-coordinate, apply lazy deletion for efficient heap removal, and implement correct sorting to avoid phantom height dips.
Master LeetCode 224 Basic Calculator by learning how a stack stores sign context — not partial results — at each opening parenthesis. Understand how to track a running result and a current sign variable so that nested expressions like -(3-(4+5)) are evaluated correctly in a single left-to-right pass.
Master LeetCode 315 Count of Smaller Numbers After Self by learning how merge sort naturally counts cross-half inversions and how a BIT approach with coordinate compression provides an alternative O(n log n) path. Understand why original index tracking is essential for both methods and how the merge step counts multiple inversions in a single comparison.
Master LeetCode 308 Range Sum Query 2D Mutable by building a 2D Binary Indexed Tree. Learn how to nest two BIT loops so that both update(row, col, val) and sumRegion(r1, c1, r2, c2) run in O(log m * log n), with the classic inclusion-exclusion formula for region sums.
Master LeetCode 407 Trapping Rain Water II by extending the 1D two-pointer technique to a 2D grid. Learn how a min-heap BFS from the boundary determines the effective water level at each interior cell, computing total trapped water in O(m*n*log(m*n)) time.
Master LeetCode 305 Number of Islands II using Union-Find with path compression and union by rank. Learn how to count islands dynamically as land is added to a grid, achieving near-O(1) amortized time per operation instead of O(m*n) BFS on every addition.
Master LeetCode 76 Minimum Window Substring using the sliding window technique with two pointers and frequency counting. Learn how to expand the right pointer to satisfy character requirements and shrink the left pointer to find the optimal window, achieving O(n) time complexity instead of O(n^2) brute force.
Master LeetCode 480 Sliding Window Median using two heaps with lazy deletion. Learn how to track elements leaving the window efficiently and why sorted containers offer a clean alternative in Python.
A full walkthrough of NeetCode's approach to every Buy and Sell Stock variant — from greedy (#121) to state machine DP (#309 and #188).
Master LeetCode 295 Find Median from Data Stream using two heaps. Learn how a max-heap and min-heap work together to compute the running median in O(log n) per number added.
LeetCode 460 LFU Cache requires O(1) get and put operations. The solution uses three maps: key-to-node, key-to-frequency, and frequency-to-doubly-linked-list. A global minFreq tracks the eviction target. On get, a key's frequency increments and it moves between buckets. On put, new keys start at frequency 1 and minFreq resets to 1, while eviction removes the LRU node from the minFreq bucket.
LeetCode 297 requires designing a Codec class with serialize and deserialize methods. Preorder DFS with null markers is the simplest approach: visit each node, emit its value or "null" for missing children, then join with commas. Deserialization uses an iterator over the split tokens, consuming one token at a time and recursively rebuilding left then right subtrees — no index tracking needed.
LeetCode 630 Course Schedule III gives you a list of courses each with a duration and a deadline. You must take courses sequentially and can only complete a course if it finishes by its deadline. The optimal solution sorts courses by deadline, greedily adds each course, and uses a max-heap to swap out the longest previous course whenever the running time exceeds a deadline — maximizing the total number of courses taken.
LeetCode 269 Alien Dictionary gives you a sorted list of words in an alien language and asks you to return a string of unique characters in the correct alien alphabet order. The solution extracts ordering constraints by comparing adjacent word pairs, builds a directed character graph, then applies Kahn's BFS topological sort. If the graph contains a cycle — or a shorter word appears after a longer prefix — the input is invalid and an empty string is returned.
LeetCode 212 Word Search II asks you to find all words from a given list that can be formed by sequentially adjacent cells on a character board. Performing DFS separately for each word leads to O(words * m*n * 4^L) time, which is too slow for large word lists. The efficient approach inserts all words into a Trie and performs a single backtracking traversal guided by Trie edges, pruning dead branches immediately and removing found words to avoid duplicates.
LeetCode 221 Maximal Square asks for the area of the largest square containing only 1s in a binary matrix. The brute-force expansion approach is cubic. The DP insight — that dp[i][j] is the side length of the largest all-1 square with bottom-right corner at (i,j), determined by the minimum of three neighbors — reduces it to O(m*n) time and O(n) space.
LeetCode 741 Cherry Pickup asks for the maximum cherries collectible on a round trip through an n x n grid. A greedy best-path-forward then best-path-back strategy fails because the two trips share cherries. The correct approach simulates two walkers moving simultaneously from start to end with 3D DP, collapsing to O(n^3) time and O(n^2) space.
LeetCode 329 Longest Increasing Path in a Matrix asks for the length of the longest strictly increasing path in an m x n integer matrix, moving in 4 directions. DFS with memoization caches the longest path from each cell so each cell is computed exactly once, giving O(m*n) time and space. A topological sort BFS on the implicit DAG — where edges go from smaller to larger neighbors — counts the number of BFS levels and equals the same answer.
LeetCode 639 Decode Ways II extends LeetCode 91 by introducing '*' as a wildcard that can represent any digit 1-9. Given an encoded string, count the number of ways to decode it modulo 10^9+7. The wildcard dramatically increases the case analysis: a single '*' contributes 9 options for single-digit decoding, while two-character pairs involving '*' require careful enumeration of valid two-digit combinations (10-26). An O(n) DP with two rolling variables handles all cases efficiently.
LeetCode 256 Paint House gives you n houses in a row and a cost matrix where costs[i][c] is the price to paint house i with color c (red, blue, or green). No two adjacent houses can share the same color. The goal is to find the minimum total cost. The key insight is that each house decision only depends on the previous house's color — a textbook state-machine DP reducible to O(1) space by tracking just three rolling values.
LeetCode 44 Wildcard Matching asks whether a pattern containing '?' (matches exactly one character) and '*' (matches any sequence including empty) fully matches a string. The key insight is that wildcard '*' is simpler than regex '*' — it stands alone without a preceding character. A 2D DP table dp[i][j] tracks whether s[0..i-1] matches p[0..j-1], with the tricky first-row initialization handling patterns of consecutive leading stars.
LeetCode 174 Dungeon Game asks for the minimum initial health for a knight to rescue the princess in an m×n grid. Each room adds or removes health; the knight must have HP ≥ 1 at every step. Forward DP fails because healing rooms ahead can mask the true minimum start. Reverse DP from the bottom-right corner — defining dp[i][j] as minimum HP needed upon entering (i,j) — resolves the dependency correctly with O(n) space.
LeetCode 688 Knight Probability in Chessboard asks for the probability a knight remains on an n×n board after k moves starting at (row, col). Each of 8 L-shaped moves is equally likely. 3D DP tracks probability at every cell after every step, and a space optimization collapses the third dimension to two rolling 2D arrays.
LeetCode 120 Triangle asks for the minimum path sum from apex to base through adjacent elements. Bottom-up DP eliminates the boundary handling that plagues top-down, and a 1D in-place array brings space from O(n²) down to O(n) with just a few lines of core logic.
LeetCode 64 Minimum Path Sum is a foundational 2D grid DP problem. Learn how to formulate the recurrence, initialize the prefix sums on the first row and column, then squeeze space from O(m×n) down to O(n) with a 1D rolling array — all in O(m×n) time.
LeetCode 377 Combination Sum IV looks like a combination problem but actually counts ordered arrangements (permutations). Learn why loop order is the key insight, how bottom-up DP solves it in O(target × n) time, and how it connects to the unbounded knapsack family including Coin Change and Coin Change II.
Learn how to solve LeetCode 131 Palindrome Partitioning by combining backtracking with a precomputed isPalindrome DP table. Instead of checking palindromes on the fly in O(n) each time, build the table in O(n²) upfront, then run backtracking with instant O(1) palindrome lookups to enumerate all valid partitions.
Learn how to solve LeetCode 10 Regular Expression Matching with 2D dynamic programming. The DP table tracks whether prefixes of the input string match prefixes of the pattern, handling the tricky zero-or-more "*" operator with an elegant two-case recurrence.
Learn how to solve LeetCode 312 Burst Balloons with interval dynamic programming. The key insight is thinking about which balloon to burst last, transforming an impossible greedy problem into an elegant O(n^3) DP solution.
Learn how to solve LeetCode 97 Interleaving String with 2D dynamic programming, space optimization, and a clear walkthrough of the recurrence relation.
Learn how to solve LeetCode 494 Target Sum with memoization and the 0/1 knapsack subset-sum transformation.
Given an array of triplets and a target triplet, determine if you can merge (take element-wise max) some triplets to form the target. Filter invalid triplets, then check if remaining maxima match the target.
A ramp in an array is a pair (i, j) where i < j and arr[i] <= arr[j]. Find the maximum width j - i. Use a monotonic decreasing stack built left-to-right, then scan right-to-left popping to find widest ramps in O(n).
Given three strings s1, s2, and s3, determine if s3 is formed by interleaving s1 and s2 while preserving their character order. Solve with 2D DP checking prefix matches, optimizable to 1D space.
Master LeetCode 1235 Maximum Profit in Job Scheduling with DP and binary search. Sort by end time, bisect for non-overlapping jobs, and build the optimal profit in O(n log n).
Implement a StockSpanner class that returns the stock span for each new price. Use a monotonic decreasing stack storing (price, span) pairs. Pop entries with price <= current, accumulate spans, and push the result.
Implement an iterator that flattens a nested list of integers. Use a stack-based lazy approach: push elements in reverse order, keep flattening the top when it is a list, and return integers on next() calls.
Build a binary tree where leaves match the given array in-order and each non-leaf node equals the product of the max leaf in its left and right subtrees. Minimize the sum of non-leaf nodes using greedy leaf removal or a monotonic stack.
Master LeetCode 362 Design Hit Counter with two approaches: a simple queue and an optimal circular buffer. The design problem that bridges algorithms and system design.
Given an array of fruit types, find the maximum number of fruits you can collect using two baskets (each holds one type). This is the classic longest subarray with at most K distinct elements problem with K=2.
A complete walkthrough of LeetCode 752 Open the Lock — BFS on an implicit state-space graph with deadends, neighbor generation, and bidirectional optimization.
Master LeetCode 239 Sliding Window Maximum with the monotonic deque approach. Learn why storing indices in a decreasing deque gives you O(n) window max.
A complete walkthrough of LeetCode #76 Minimum Window Substring, the Hard sliding window problem that tests frequency counting, variable windows, and the expand-shrink pattern.
Given a height matrix with Pacific ocean on top/left and Atlantic on bottom/right, find cells where water can flow to both oceans. DFS/BFS from each ocean border uphill, then intersect the reachable sets.
Given strings s and t, return the number of distinct subsequences of s which equals t. Build a 2D DP table tracking how many ways to form each prefix of t from each prefix of s, with an optional 1D space optimization.
Master the stock span problem on LeetCode with a monotonic decreasing stack. Learn the O(1) amortized solution for Online Stock Span (#901) step by step.
Given a string s and integer k, repeatedly remove k adjacent duplicate characters until no more removals are possible. Use a stack of (char, count) pairs to process all removals in a single O(n) pass.
A complete walkthrough of LeetCode 137 Single Number II, covering why XOR fails for triples, the bit counting modulo 3 technique, and edge cases.
Master LeetCode 621 Task Scheduler with the greedy formula approach — no simulation needed. Understand the math behind CPU task scheduling with cooldowns.
Master LeetCode #127 Word Ladder with BFS on an implicit graph. Learn why words are nodes, one-letter changes are edges, and how pattern-based adjacency speeds up your solution.
Two players take turns picking stones from either end of a row of piles. Prove the first player always wins mathematically, or solve the general case with interval DP where dp[i][j] tracks the advantage over the subarray.
Master LeetCode 516 with the LCS trick and direct DP. Walk through examples, edge cases, and the key insight that LPS(s) = LCS(s, reverse(s)).
A turbulent subarray alternates between increasing and decreasing comparisons. Track inc and dec counters: arr[i]>arr[i-1] means inc=dec+1, arr[i]<arr[i-1] means dec=inc+1, equal resets both. Return the maximum.
A step-by-step walkthrough of LeetCode 424: Longest Repeating Character Replacement using a sliding window with frequency tracking.
Two approaches to LeetCode 341 Flatten Nested List Iterator — upfront flatten and lazy stack-based — with edge cases and complexity analysis.
A step-by-step Union-Find walkthrough for LeetCode 721 Accounts Merge, the most practical connected-components problem on LeetCode.
Learn how to construct a binary tree from preorder and inorder traversal arrays with a clear recursive approach and O(n) hash map optimization.
Complete walkthrough of LeetCode 37 Sudoku Solver. Learn the backtracking approach with O(1) constraint checking using sets for rows, columns, and boxes.
Given n cities and flights with prices, find the cheapest route from src to dst with at most k stops. Use Bellman-Ford limited to k+1 rounds, BFS tracking costs per level, or modified Dijkstra with stop counting.
A complete walkthrough of LeetCode 229 Majority Element II using extended Boyer-Moore Voting with two candidates in O(n) time and O(1) space.
Master Edit Distance (#72) with a complete walkthrough of the 2D DP table, recurrence relation, and space optimization. The framework behind every string DP problem.
Learn the monotonic stack pattern through LeetCode 739 Daily Temperatures. Clear O(n) solution with decreasing stack walkthrough and edge cases.
Given an array of words and an integer k, return the k most frequent words sorted by frequency descending then lexicographic order. Solve with a hash map plus min-heap or bucket sort approach.
A complete walkthrough of LeetCode 1143 Longest Common Subsequence with 2D DP table construction, visual explanation, and space optimization to O(min(m,n)).
Learn how Partition Equal Subset Sum (#416) reduces to subset sum DP — the most common boolean knapsack problem on LeetCode.
A complete walkthrough of Redundant Connection (#684) using Union-Find with path compression and union by rank to detect the cycle-creating edge in near-linear time.
Given an encoded string with letters and digits (where a digit d repeats the preceding string d times), find the k-th character without building the decoded string. Use a forward-backward simulation with modular arithmetic.
A complete walkthrough of LeetCode 124 Binary Tree Maximum Path Sum. Learn the key recursive insight, edge cases, and the return-one-track-another pattern.
A complete walkthrough of LeetCode 355 Design Twitter — data structures, news feed merge, and the OOP design that makes it all work.
Master the Meeting Rooms II problem with the min-heap and sweep line approaches — the #1 interval + heap question at top tech companies.
Given a binary matrix with exactly two islands, find the minimum number of 0s you must flip to 1 to connect the islands. DFS marks one island, then multi-source BFS finds the shortest bridge to the other.
Master LeetCode 300 — Longest Increasing Subsequence — with both the O(n²) DP and O(n log n) binary search solutions, plus a visual step-by-step walkthrough.
A complete walkthrough of LeetCode 133 Clone Graph covering BFS and DFS solutions, the essential hash map pattern, and how to handle cycles during deep copy.
Given a binary tree, return the values of nodes visible from the right side, top to bottom. Use BFS level-order traversal collecting the last element of each level, or DFS visiting right subtree first.
Master Course Schedule (#207) with BFS (Kahn's algorithm) and DFS cycle detection — the definitive topological sort problem walkthrough.
Master LeetCode #138 Copy List with Random Pointer with two approaches: hash map cloning and the O(1) space interleaving technique.
Given an array of integers, find the sum of min(subarray) for all subarrays. Use a monotonic increasing stack to determine how many subarrays each element is the minimum of, then sum the contributions in O(n) time.
A complete walkthrough of Word Break (LeetCode #139) covering memoization, bottom-up DP, and BFS approaches with complexity analysis and edge cases.
Given a BST and integer k, return the k-th smallest element. Since inorder traversal of a BST yields sorted order, perform inorder and count to k. Use an iterative stack for O(H+k) time with early exit.
How to solve Longest Consecutive Sequence (#128) in O(n) using a hash set — the key insight is only counting from sequence beginnings.
Partition a string into as many parts as possible so that each letter appears in at most one part. Use a greedy approach: track last occurrences, expand partition boundaries, and cut when the current index reaches the boundary.
Master LeetCode 42 with three clear approaches: brute force, prefix max arrays, and the optimal two-pointer technique in O(n) time and O(1) space.
Given n balloons with values, bursting balloon i earns nums[i-1]*nums[i]*nums[i+1] coins. Find the maximum coins by bursting all balloons. Use interval DP with reverse thinking: choose the last balloon to burst in each subproblem.
Complete walkthrough of LeetCode 91 Decode Ways — Fibonacci DP with string validation, zero handling, and O(1) space optimization.
Given a balanced parentheses string, compute its score using the recursive rules: () = 1, AB = A+B, (A) = 2*A. Solve with a stack tracking scores per depth, or an O(1) space depth counter adding 2^depth at each leaf pair.
A complete walkthrough of LeetCode 547 Number of Provinces, covering DFS and Union-Find approaches on an adjacency matrix with visual examples and edge cases.
Solve LeetCode 238 without division using prefix and suffix products in O(n) time and O(1) extra space. A complete walkthrough with edge cases.
A complete walkthrough of LeetCode 735 Asteroid Collision — learn the stack simulation approach, handle every collision case, and master this creative Medium problem.
Master LeetCode 973 with three approaches: sort, max-heap, and quickselect. Learn how the Top K pattern applies to distance problems with clear complexity analysis.
Master LeetCode 73 Set Matrix Zeroes with the O(1) space in-place marker technique. Learn how to use the matrix itself as storage to eliminate extra arrays.
Master the Gas Station problem (#134) with the greedy one-pass approach — learn why total gas >= total cost guarantees a solution and how to find the starting index in O(n).
A complete walkthrough of LeetCode 322 Coin Change covering why greedy fails, top-down memoization, bottom-up tabulation, and the DP framework that transfers to 30+ problems.
Given a string of dominoes with L, R, and dot characters, determine the final state after all dominoes have fallen. Process segments between adjacent forces to resolve collisions in O(n) time.
Learn why tracking both min and max solves LeetCode 152 (Maximum Product Subarray) in O(n) time with a clear walkthrough and edge case guide.
Master LeetCode 435 with the greedy interval scheduling approach — sort by end time, count removals, and ace interval problems in interviews.
Master the transpose + reverse approach to rotate a matrix 90 degrees clockwise in place — the elegant O(1) space solution to LeetCode 48.
Given a string s and an array of words, count how many words are subsequences of s. Avoid checking each word naively against s by preprocessing s into character index lists and using binary search or bucket iterators.
A step-by-step walkthrough of Search in Rotated Sorted Array (#33) — the key insight, implementation, visual example, and edge cases for this FAANG favorite.
Learn the greedy level-by-level strategy to solve Jump Game II (#45) in O(n) time with O(1) space.
A complete walkthrough of LeetCode 54 Spiral Matrix using the boundary approach — four pointers, shrink inward, and handle every edge case.
Master LeetCode 55 with the greedy reachability approach — one variable, one pass, O(n) time.
On an n x n grid where water rises to level t at time t, find the minimum time to swim from (0,0) to (n-1,n-1). Use Dijkstra tracking the max elevation on the path, or binary search on the answer with BFS feasibility check.
Master Kth Largest Element (#215) with heap and quickselect approaches. Learn the trade-offs interviewers expect you to discuss.
A complete walkthrough of LeetCode 57 Insert Interval — the three-phase approach to inserting and merging intervals in O(n) time.
A step-by-step walkthrough of Find Minimum in Rotated Sorted Array (#153), the binary search pattern for rotated arrays.
Count the number of prime numbers strictly less than n. The Sieve of Eratosthenes marks composites in O(n log log n) time, far faster than checking each number individually for primality.
Solve LeetCode 567 Permutation in String using a fixed-size sliding window and character frequency counting for an elegant O(n) approach.
A complete walkthrough of Find First and Last Position (#34) — two modified binary searches that find the left and right boundaries of a target value in a sorted array.
Design an algorithm to serialize a binary tree to a string and deserialize it back. Preorder traversal with null markers uniquely encodes any tree. Deserialize by consuming tokens left-to-right with recursive reconstruction.
A complete walkthrough of Merge Intervals (#56) covering the sort-and-sweep approach, visual examples, edge cases, and the interval pattern that applies to dozens of related problems.
A clear walkthrough of LeetCode 114 Flatten Binary Tree to Linked List, covering recursive and Morris-like iterative approaches with visual examples.
Master LeetCode 695 Max Area of Island with DFS cell counting. Same traversal as Number of Islands but each DFS returns the connected component size.
Find the minimum element in a rotated sorted array that may contain duplicates. Extend the classic binary search by handling the ambiguous case where nums[mid] == nums[right] by decrementing right one step at a time.
Master the 3Sum problem (#15) with the optimal sort + two pointers approach. Learn how to handle duplicates cleanly and extend the pattern to 4Sum and beyond.
A complete walkthrough of LeetCode 394: Decode String. Learn the stack approach for nested bracket decoding with a visual step-by-step trace.
A clear walkthrough of LeetCode 199 Binary Tree Right Side View covering BFS and DFS approaches with visual examples and edge cases.
Implement wildcard pattern matching where ? matches any single character and * matches any sequence of characters. Solve with 2D boolean DP or a greedy two-pointer approach with star backtracking.
A complete walkthrough of Number of Islands (#200) covering DFS, BFS, and Union-Find solutions with complexity analysis and related grid traversal problems.
Learn the monotonic stack + hash map approach to solve LeetCode 496 (Next Greater Element I) in O(n) time with a clear visual walkthrough.
Two clean approaches to LeetCode 98 Validate Binary Search Tree — range checking and inorder traversal — with edge cases and complexity analysis.
Given an array of positive integers, determine if it can be partitioned into two subsets with equal sum. Reduce to the subset sum problem targeting total/2 and solve with 0/1 knapsack DP in O(n * target) time.
Master LeetCode 146 LRU Cache with the optimal HashMap + Doubly Linked List solution. Step-by-step walkthrough with edge cases and interview tips.
Design a data structure that supports updating an element and querying the sum of a range, both in O(log n). Implement with a segment tree for flexibility or a Fenwick tree for simplicity.
A complete walkthrough of LeetCode #225 Implement Stack Using Queues — learn two approaches (costly push vs costly pop) and why costly push is preferred in interviews.
Master LeetCode 232 Implement Queue Using Stacks with two approaches. Learn why the lazy transfer technique gives amortized O(1) for all operations.
Master the backtracking template with LeetCode 46 Permutations — the choose-explore-unchoose pattern that applies to every recursive exploration problem.
A complete walkthrough of LeetCode 148 Sort List — merge sort on a linked list using find middle, split, and merge.
Master LeetCode 17 Letter Combinations of a Phone Number with a clean backtracking approach. The simplest backtracking problem and the ideal starting point.
Master LeetCode 11 Container With Most Water with the two-pointer approach. Learn why moving the shorter line inward gives you an O(n) solution.
Evaluate an arithmetic expression in Reverse Polish Notation (postfix). Use a stack to process tokens left-to-right: push numbers, pop two operands on operators, compute, and push the result back.
A complete walkthrough of LeetCode 209 — Minimum Size Subarray Sum — using the variable-size sliding window technique with visual examples and edge cases.
Learn how to design a HashMap from scratch with LeetCode 706 — hash functions, chaining collisions, and the bucket array architecture explained step by step.
Master LeetCode 22 Generate Parentheses with constraint-based backtracking. Two rules, zero invalid combinations, and a clean decision tree walkthrough.
Master the Two Sum LeetCode problem with brute force and optimal hash map solutions, edge cases, and the complement-search pattern that unlocks dozens of problems.
Find the longest strictly increasing path in a matrix where you can move in four directions. Use DFS with memoization on the implicit DAG, or topological sort with BFS layer peeling, both in O(m*n) time.
Master palindrome linked list with two approaches: array copy and the optimal O(1) space reverse-half technique using fast/slow pointers.
Master the House Robber problem with a clear DP walkthrough. Learn the Fibonacci-style recurrence and space optimization that interviewers love.
A complete walkthrough of LeetCode #230 Kth Smallest Element in a BST — learn why inorder traversal gives sorted order and how to stop early with a stack.
Master LeetCode 49 Group Anagrams with two approaches: sorted string key and character count key. Learn the hash map grouping pattern used across dozens of interview problems.
Implement regular expression matching supporting . and * operators. Use 2D boolean DP where dp[i][j] tracks if s[0..i-1] matches p[0..j-1]. The star operator branches into zero-match and extend-match cases.
Three complete approaches to LeetCode 78 Subsets: backtracking, iterative, and bit manipulation with complexity analysis and edge cases.
Master LeetCode #3 with a clear walkthrough from brute force to optimal sliding window. Learn the variable-size window pattern used in dozens of interview problems.
Solve LeetCode 74 by treating the sorted matrix as a flattened array and running a single binary search in O(log(m*n)) time.
Design a data structure that supports adding numbers from a stream and finding the median at any time. Use two heaps — a max-heap for the smaller half and min-heap for the larger half — to maintain O(log n) insertion and O(1) median retrieval.
Master LeetCode 64 Minimum Path Sum with the weighted grid DP approach. Step-by-step walkthrough with in-place optimization and edge cases.
Find the contiguous subarray with the largest product. Unlike maximum sum (Kadane), negatives can flip signs. Track curMax and curMin simultaneously — when multiplied by a negative, max becomes min and vice versa.
Master Climbing Stairs (#70) with three approaches: recursion, memoization, and tabulation. Learn the Fibonacci DP pattern that unlocks House Robber, Decode Ways, and more.
Master LeetCode 235 Lowest Common Ancestor of BST. Learn how the BST ordering property lets you find LCA in O(h) time with a simple iterative approach.
Master LeetCode 543 Diameter of Binary Tree with DFS. Learn the dual-value recursion pattern: return height, track diameter globally.
A complete walkthrough of LeetCode 62 Unique Paths covering the 2D DP approach, space optimization to O(n), and the combinatorics shortcut.
Solve LeetCode 338 Counting Bits with a single-line DP recurrence that combines right-shift and bitwise AND to count 1-bits for every number from 0 to n in O(n) time.
Master LeetCode 141 with Floyd's cycle detection algorithm. Learn the hash set approach, then the optimal fast/slow pointer solution with O(1) space.
Master Kadane's algorithm to solve Maximum Subarray (#53) in O(n) time. Understand the extend-or-restart decision that powers contiguous sum problems.
Master LeetCode 155 Min Stack with two clean approaches. Learn the two-stack and single-stack-with-pairs techniques for O(1) getMin.
Solve LeetCode 326 Power of Three with two approaches: the loop method and the brilliant O(1) max power trick using 3^19.
A step-by-step walkthrough of LeetCode 8 String to Integer (atoi) covering whitespace, signs, overflow clamping, and every edge case you need to handle.
A step-by-step walkthrough of LeetCode 290 Word Pattern using bidirectional hash maps, with visual examples and edge case analysis.
A complete walkthrough of LeetCode 387 First Unique Character in a String using the two-pass frequency count approach in O(n) time.
Master LeetCode 121 — Best Time to Buy and Sell Stock. Learn the one-pass greedy approach that solves it in O(n) time with O(1) space.
A complete walkthrough of LeetCode #350 Intersection of Two Arrays II — hash map frequency counting and the sort + two pointers alternative.
Master LeetCode 171 Excel Sheet Column Number with the base-26 conversion approach. Step-by-step walkthrough of letter to number conversion with visual examples.
Master the intersection of two linked lists with the beautiful two-pointer approach that equalizes path lengths in O(1) space.
Isomorphic Strings (#205) requires two hash maps for bidirectional character mapping — the same pattern behind Word Pattern, shifted strings, and structural equivalence.
Solve LeetCode 190 Reverse Bits by extracting each bit with n & 1, placing it into the result with left-shift and OR, then advancing. 32 iterations, O(1) time and space.
Two approaches to LeetCode 202 Happy Number — hash set tracking and Floyd's cycle detection — showing how the same fast/slow technique from Linked List Cycle applies to number sequences.
Solve LeetCode 191 Number of 1 Bits using the n & (n-1) trick to clear the lowest set bit each iteration. Count Hamming weight in O(k) where k is the number of 1-bits.
Learn the n & (n-1) bit trick that solves Power of Two in O(1) time and unlocks an entire category of bit manipulation problems.
Learn how LeetCode 746 (Min Cost Climbing Stairs) extends Climbing Stairs with a weighted Fibonacci DP recurrence, O(1) space optimization, and visual walkthrough.
Master both iterative and recursive approaches to Reverse Linked List (#206). Learn the three-pointer technique that forms the foundation of linked list manipulation.
A complete walkthrough of LeetCode #118 Pascal's Triangle — build each row from the previous one using the simplest DP pattern.
A step-by-step walkthrough of LeetCode 69 Sqrt(x) using binary search on the answer space, with a visual trace for x=8 and overflow-safe implementation tips.
A complete walkthrough of LeetCode 35 Search Insert Position — the lower bound binary search pattern that forms the foundation for dozens of harder problems.
Implement a trie (prefix tree) supporting insert, search, and startsWith operations. Each TrieNode stores children and a word-end flag. All operations run in O(m) time where m is the word length.
A complete walkthrough of Missing Number (LeetCode 268) covering the Gauss formula, XOR, and hash set approaches with trade-off analysis.
Learn how to solve Valid Parentheses (LeetCode #20) with a stack — step-by-step walkthrough, visual examples, edge cases, and the LIFO pattern that applies to dozens of interview problems.
Boyer-Moore Voting solves Majority Element (#169) in O(n) time and O(1) space — one of the most elegant algorithms in CS, explained step by step.
Learn how to solve LeetCode 572 Subtree of Another Tree by composing Same Tree with DFS traversal for an elegant recursive solution.
Master LeetCode 724 Find Pivot Index with the prefix sum approach. Learn the one-variable trick to find where left sum equals right sum in O(n) time.
A step-by-step walkthrough of LeetCode 67 Add Binary, covering right-to-left digit processing, carry propagation, and why this problem shares the same core pattern as Add Two Numbers.
Master LeetCode 24 — swap adjacent linked list nodes by rewiring pointers, not values. Iterative and recursive approaches explained step by step.
Find the unique element in an array where every other number appears twice — using XOR in O(n) time and O(1) space.
A complete walkthrough of LeetCode 19 — Remove Nth Node From End of List — using the two pointer gap technique with a dummy node for clean edge case handling.
Master LeetCode 242 Valid Anagram with sorting and frequency counting approaches, plus the edge cases interviewers expect you to handle.
Given strings s and t, find the minimum window in s that contains all characters of t including duplicates. Use a sliding window with frequency maps, expanding right to satisfy and shrinking left to minimize.
A clean walkthrough of LeetCode 383 Ransom Note using character frequency counting with a hash map in O(m+n) time.
Master LeetCode 102 with a clear BFS queue template. Step-by-step level order traversal walkthrough with visual examples and edge cases.
A complete walkthrough of LeetCode #278 First Bad Version — apply the "find first true" binary search template with minimum API calls.
A complete walkthrough of Merge Two Sorted Lists (#21) covering iterative and recursive approaches, the dummy node technique, and edge cases.
A complete walkthrough of LeetCode #2 Add Two Numbers — learn the dummy node technique, carry propagation, and the linked list addition pattern.
Middle of the Linked List (#876) is the simplest fast/slow pointer problem — one pointer moves twice as fast, so when fast reaches the end, slow is at the middle.
Solve Is Subsequence (#392) with a clean two-pointer approach in O(n+m) time and O(1) space — the foundation for every subsequence problem.
Binary Search (#704) is the Hello World of binary search — learn the core template that powers every variant.
A complete walkthrough of LeetCode 167 Two Sum II, covering the two-pointer approach on sorted input, why it works, visual examples, and edge cases.
Master LeetCode 104 Maximum Depth of Binary Tree with DFS recursive and BFS iterative solutions, visual walkthrough, and edge cases.
A complete walkthrough of LeetCode 28 Find the Index of the First Occurrence in a String, covering brute force, built-in vs manual approaches, edge cases, and why KMP is overkill for interviews.
Find the median of two sorted arrays in O(log(min(m,n))) time. Binary search partitions the shorter array so that the combined left halves equal the merged lower half. Cross-compare boundary elements to validate.
A complete walkthrough of LeetCode 217 Contains Duplicate — from brute force to the optimal hash set solution with O(n) time complexity.
Master LeetCode 283 Move Zeroes with the two-pointer swap technique. Learn the in-place partition pattern that forms the foundation for harder array problems.
Master Remove Duplicates from Sorted Array (LeetCode 26) with the slow/fast two-pointer pattern. One pass, O(1) space, clean code.
A complete walkthrough of LeetCode 66 Plus One, covering the carry propagation pattern, edge cases like all-nines, and how this pattern connects to harder linked list problems.
Learn how to solve LeetCode 13 Roman to Integer using a hash map and the subtraction rule. Step-by-step walkthrough with visual example.
Master LeetCode 125 Valid Palindrome with the two-pointer approach. Learn character filtering, case-insensitive comparison, and O(1) space technique.
Two clean approaches to LeetCode 58: split-based one-liner and optimal reverse iteration with O(1) space.
A complete walkthrough of LeetCode 226 Invert Binary Tree with recursive DFS and iterative BFS solutions, visual examples, and edge cases.
A complete walkthrough of LeetCode 9 Palindrome Number, covering the half-reversal technique that avoids string conversion for an O(1) space, O(log n) time solution.
A complete walkthrough of LeetCode 27 Remove Element, covering the two-pointer approach, swap-with-end optimization, visual examples, and edge cases.
Master LeetCode 101 Symmetric Tree with recursive and iterative approaches. Learn the mirror comparison pattern that builds directly on Same Tree (#100).
Master LeetCode 412 Fizz Buzz with the classic modulo approach and the extensible string concatenation method. The question that started it all.
Learn how to solve LeetCode 100 Same Tree with recursive DFS and BFS approaches, plus the dual-recursion pattern behind every tree comparison problem.
A complete walkthrough of LeetCode 344 Reverse String using the two-pointer swap technique with O(n) time and O(1) space.
A complete walkthrough of LeetCode 88 Merge Sorted Array, covering the three-pointer merge-from-end technique, visual step-by-step trace, and edge cases.