LeetCode 150: Solutions and Notes
Solutions and notes for 150 LeetCode problems covering fundamental patterns in data structures and algorithms.
Arrays & Hashing
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 1 | Contains Duplicate | Hash Set | Set lookup for O(1) existence check |
| 2 | Valid Anagram | Hash Map | Compare character frequency counts |
| 3 | Two Sum | Hash Map | Store seen values, look up complement (target - num) |
| 4 | Group Anagrams | Hash Map | Sorted string or char count tuple as dict key |
| 5 | Top K Frequent Elements | Bucket Sort | Bucket index = frequency, avoid O(n log n) sort |
| 6 | Product of Array Except Self | Prefix / Suffix | Left pass times right pass, no division |
| 7 | Valid Sudoku | Hash Set | Track seen per row, column, and 3x3 box |
| 8 | Encode and Decode Strings | Design | Prefix each string with its length + delimiter |
| 9 | Longest Consecutive Sequence | Hash Set | Only count from sequence starts (num-1 not in set) |
Two Pointers
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 10 | Valid Palindrome | Two Pointers | Compare from both ends, skip non-alphanumeric |
| 11 | Two Sum II | Two Pointers | Sorted array: move left up if too small, right down if too big |
| 12 | 3Sum | Sort + Two Pointers | Fix one element, two-pointer on remainder, skip duplicates |
| 13 | Container With Most Water | Two Pointers | Always move the shorter side inward |
| 14 | Trapping Rain Water | Two Pointers | Water at position = min(left_max, right_max) - height |
Sliding Window
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 15 | Best Time to Buy and Sell Stock | Sliding Window | Track min price so far, max profit at each step |
| 16 | Longest Substring Without Repeating Characters | Window + Set | Shrink left when duplicate found |
| 17 | Longest Repeating Character Replacement | Sliding Window | Window valid when length - max_freq <= k |
| 18 | Permutation in String | Fixed Window | Compare frequency maps of window and target |
| 19 | Minimum Window Substring | Sliding Window | Expand to cover all chars, shrink to minimize |
| 20 | Sliding Window Maximum | Monotonic Deque | Deque stores indices in decreasing value order |
Stack
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 21 | Valid Parentheses | Stack | Push open, pop and match on close |
| 22 | Min Stack | Two Stacks | Auxiliary stack tracks current minimum |
| 23 | Evaluate Reverse Polish Notation | Stack | Push numbers, pop two on operator |
| 24 | Generate Parentheses | Backtracking | Track open/close counts, add when valid |
| 25 | Daily Temperatures | Monotonic Stack | Pop when current temp > stack top, record gap |
| 26 | Car Fleet | Sort + Stack | Sort by position, stack by time to target |
| 27 | Largest Rectangle in Histogram | Monotonic Stack | Pop when shorter bar found, width extends back to previous stack element |
Binary Search
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 28 | Binary Search | Binary Search | Standard left <= right template |
| 29 | Search a 2D Matrix | Binary Search | Treat 2D matrix as sorted 1D array |
| 30 | Koko Eating Bananas | BS on Answer | Binary search on speed, check feasibility |
| 31 | Find Minimum in Rotated Sorted Array | Modified BS | Compare mid to right to find rotation point |
| 32 | Search in Rotated Sorted Array | Modified BS | Determine which half is sorted, search accordingly |
| 33 | Time Based Key-Value Store | Binary Search | Binary search on timestamps for floor value |
| 34 | Median of Two Sorted Arrays | Binary Search | Binary search on partition of shorter array |
Linked List
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 35 | Reverse Linked List | Iteration | Track prev, curr, next; reassign pointers |
| 36 | Merge Two Sorted Lists | Two Pointers | Compare heads, append smaller |
| 37 | Reorder List | Fast/Slow + Reverse | Find middle, reverse second half, interleave |
| 38 | Remove Nth Node From End | Two Pointers | Advance fast pointer n steps ahead |
| 39 | Copy List with Random Pointer | Hash Map | Map old nodes to new nodes, then assign pointers |
| 40 | Add Two Numbers | Iteration | Add digit by digit with carry |
| 41 | Linked List Cycle | Fast/Slow | Floyd’s: fast moves 2x, slow moves 1x, they meet in cycle |
| 42 | Find the Duplicate Number | Floyd’s Cycle | Treat values as next pointers, detect cycle start |
| 43 | LRU Cache | Hash Map + DLL | O(1) lookup with map, O(1) eviction with doubly linked list |
| 44 | Merge K Sorted Lists | Min Heap | Push all heads, pop min, push its next |
| 45 | Reverse Nodes in K-Group | Iteration | Reverse k nodes at a time, connect groups |
Trees
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 46 | Invert Binary Tree | DFS | Swap left and right children recursively |
| 47 | Maximum Depth of Binary Tree | DFS | 1 + max(left depth, right depth) |
| 48 | Diameter of Binary Tree | DFS | Track max of left_depth + right_depth at each node |
| 49 | Balanced Binary Tree | DFS | Return -1 early if height diff > 1 at any node |
| 50 | Same Tree | DFS | Recursively compare values and structure |
| 51 | Subtree of Another Tree | DFS | Check isSameTree at every node |
| 52 | Lowest Common Ancestor of BST | BST Property | Go left if both smaller, right if both larger, else found |
| 53 | Binary Tree Level Order Traversal | BFS | Queue-based level-by-level processing |
| 54 | Binary Tree Right Side View | BFS | Last node at each level |
| 55 | Count Good Nodes | DFS | Track max value along path from root |
| 56 | Validate BST | DFS | Pass valid (min, max) range down recursively |
| 57 | Kth Smallest in BST | Inorder | Inorder traversal gives sorted order; return kth |
| 58 | Construct from Preorder + Inorder | Recursion | Preorder root splits inorder into left/right subtrees |
| 59 | Binary Tree Max Path Sum | DFS | At each node: max(left,0) + val + max(right,0); track global max |
| 60 | Serialize/Deserialize Binary Tree | Preorder DFS | Null markers + iterator for deserialization |
Tries
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 61 | Implement Trie | Trie | Dict of children per node + end-of-word flag |
| 62 | Design Add and Search Words | Trie + DFS | DFS branch on ‘.’ wildcard, normal lookup otherwise |
| 63 | Word Search II | Trie + Backtracking | Build trie from words, DFS on grid |
Heap / Priority Queue
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 64 | Kth Largest Element in a Stream | Min Heap | Maintain heap of size k; top is kth largest |
| 65 | Last Stone Weight | Max Heap | Pop two largest, push difference if nonzero |
| 66 | K Closest Points to Origin | Max Heap | Heap of size k by distance |
| 67 | Kth Largest Element in an Array | Quickselect | Partition around pivot, recurse on correct side |
| 68 | Task Scheduler | Greedy + Heap | Most frequent first; idle slots = (max_freq-1) * (n+1) |
| 69 | Design Twitter | Heap + Hash Map | Merge k sorted feeds with heap |
| 70 | Find Median from Data Stream | Two Heaps | Max heap for lower half, min heap for upper half |
Backtracking
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 71 | Subsets | Backtracking | Include or exclude each element |
| 72 | Combination Sum | Backtracking | Allow reuse of same element, sort to prune |
| 73 | Permutations | Backtracking | Swap or visited set to build permutations |
| 74 | Subsets II | Backtracking | Sort first, skip consecutive duplicates |
| 75 | Combination Sum II | Backtracking | Sort + skip duplicates, each element used once |
| 76 | Word Search | DFS + Backtracking | DFS on grid, mark visited, backtrack |
| 77 | Palindrome Partitioning | Backtracking | Try every prefix that’s a palindrome, recurse on rest |
| 78 | Letter Combinations of Phone | Backtracking | Map digits to letters, build combinations |
| 79 | N-Queens | Backtracking | Track columns, diagonals, anti-diagonals |
Graphs
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 80 | Number of Islands | DFS/BFS | Flood fill from each unvisited ‘1’, count components |
| 81 | Clone Graph | DFS + Hash Map | Map old node to new node, recurse on neighbors |
| 82 | Max Area of Island | DFS | Flood fill counting cells; track max |
| 83 | Pacific Atlantic Water Flow | DFS from Edges | Start from ocean edges, flow inward; intersect results |
| 84 | Surrounded Regions | DFS from Border | Mark border-connected O’s, flip the rest |
| 85 | Rotting Oranges | Multi-source BFS | BFS from all rotten simultaneously; count levels |
| 86 | Walls and Gates | Multi-source BFS | BFS from all gates simultaneously |
| 87 | Course Schedule | Topological Sort | Detect cycle in directed graph via DFS |
| 88 | Course Schedule II | Topological Sort | Return valid ordering, or empty if cycle |
| 89 | Redundant Connection | Union Find | Edge that creates a cycle |
| 90 | Connected Components | Union Find / DFS | Count distinct components |
| 91 | Graph Valid Tree | Union Find | n-1 edges + no cycle = tree |
| 92 | Word Ladder | BFS | BFS on word graph; change one letter at a time |
Advanced Graphs
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 93 | Reconstruct Itinerary | Euler Path | Hierholzer’s algorithm; sorted adjacency list |
| 94 | Min Cost to Connect All Points | Prim’s / Kruskal’s | Minimum spanning tree |
| 95 | Network Delay Time | Dijkstra’s | Shortest path from source to all nodes; return max |
| 96 | Swim in Rising Water | Dijkstra’s | Min max-elevation path via priority queue |
| 97 | Alien Dictionary | Topological Sort | Build graph from adjacent word comparisons |
| 98 | Cheapest Flights Within K Stops | Bellman-Ford | K+1 iterations of edge relaxation |
1-D Dynamic Programming
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 99 | Climbing Stairs | DP | dp[i] = dp[i-1] + dp[i-2] (Fibonacci) |
| 100 | Min Cost Climbing Stairs | DP | dp[i] = cost[i] + min(dp[i-1], dp[i-2]) |
| 101 | House Robber | DP | dp[i] = max(dp[i-1], dp[i-2] + nums[i]) |
| 102 | House Robber II | DP | Circular: run House Robber twice, skip first or last |
| 103 | Longest Palindromic Substring | Expand from Center | Try each center and each pair, expand outward |
| 104 | Palindromic Substrings | Expand from Center | Count palindromes expanding from each center |
| 105 | Decode Ways | DP | dp[i] from valid single-digit and double-digit decodings |
| 106 | Coin Change | DP | dp[amount] = min(dp[amount - coin] + 1) for each coin |
| 107 | Maximum Product Subarray | DP | Track both max and min product (negative * negative) |
| 108 | Word Break | DP | dp[i] = true if any dp[j] and s[j:i] is a word |
| 109 | Longest Increasing Subsequence | DP / Binary Search | Binary search on tails array for O(n log n) |
| 110 | Partition Equal Subset Sum | DP (0/1 Knapsack) | Target = total/2; boolean dp on reachable sums |
2-D Dynamic Programming
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 111 | Unique Paths | DP | dp[i][j] = dp[i-1][j] + dp[i][j-1] |
| 112 | Longest Common Subsequence | DP | Match: dp[i-1][j-1]+1; else max(dp[i-1][j], dp[i][j-1]) |
| 113 | Buy/Sell Stock with Cooldown | State Machine DP | Three states: hold, sold, rest; transitions between them |
| 114 | Coin Change II | DP (Unbounded Knapsack) | Iterate coins then amounts to avoid counting duplicates |
| 115 | Target Sum | DP (Subset Sum) | Reduce to: find subset with sum (total + target) / 2 |
| 116 | Interleaving String | 2D DP | dp[i][j] = can s1[:i] and s2[:j] form s3[:i+j] |
| 117 | Longest Increasing Path in Matrix | DFS + Memo | DFS from each cell, cache results |
| 118 | Distinct Subsequences | DP | dp[i][j] = dp[i-1][j] + (dp[i-1][j-1] if chars match) |
| 119 | Edit Distance | DP | Insert/delete/replace: min of three subproblems + 1 |
| 120 | Burst Balloons | Interval DP | Choose last balloon to burst in each interval |
| 121 | Regular Expression Matching | DP | Handle ‘.’ (any char) and ‘*’ (zero or more of preceding) |
Greedy
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 122 | Maximum Subarray | Kadane’s | Reset running sum to current element when it goes negative |
| 123 | Jump Game | Greedy | Track farthest reachable index |
| 124 | Jump Game II | Greedy (BFS) | BFS levels = minimum jumps |
| 125 | Gas Station | Greedy | If total gas >= total cost, start where running deficit resets |
| 126 | Hand of Straights | Greedy + Hash Map | Greedily form groups starting from smallest card |
| 127 | Merge Triplets to Form Target | Greedy | Only use triplets where no element exceeds target |
| 128 | Partition Labels | Greedy | Track last occurrence of each char; extend partition end |
| 129 | Valid Parenthesis String | Greedy | Track min/max possible open count |
Intervals
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 130 | Insert Interval | Sweep | Add non-overlapping before/after, merge overlapping |
| 131 | Merge Intervals | Sort + Sweep | Sort by start; merge if current overlaps previous |
| 132 | Non-overlapping Intervals | Greedy | Sort by end; count overlaps to remove |
| 133 | Meeting Rooms | Sort | Sort by start, check for any overlap |
| 134 | Meeting Rooms II | Sweep / Heap | Min heap on end times tracks concurrent meetings |
| 135 | Min Interval for Each Query | Sort + Heap | Sort intervals and queries; min heap by interval size |
Math & Geometry
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 136 | Rotate Image | Matrix | Transpose, then reverse each row |
| 137 | Spiral Matrix | Simulation | Shrink boundaries after each direction |
| 138 | Set Matrix Zeroes | In-place Marking | Use first row/column as markers |
| 139 | Happy Number | Cycle Detection | Floyd’s or hash set to detect repeating digit-square sums |
| 140 | Plus One | Math | Carry propagation from least significant digit |
| 141 | Pow(x, n) | Fast Exponentiation | Square and multiply; handle negative exponent |
| 142 | Multiply Strings | Math | Digit-by-digit multiplication into positions i+j, i+j+1 |
| 143 | Detect Squares | Hash Map | Store points; for each query point, find valid square corners |
Bit Manipulation
| # | Problem | Pattern | Key Idea |
|---|---|---|---|
| 144 | Single Number | XOR | XOR all numbers; duplicates cancel out |
| 145 | Number of 1 Bits | Bit Trick | n & (n-1) clears lowest set bit; count iterations |
| 146 | Counting Bits | DP + Bits | dp[i] = dp[i » 1] + (i & 1) |
| 147 | Reverse Bits | Bit Manipulation | Shift result left, add LSB of n, shift n right |
| 148 | Missing Number | XOR / Math | XOR with indices, or expected sum minus actual sum |
| 149 | Sum of Two Integers | Bit Manipulation | XOR for sum without carry; (a & b) « 1 for carry |
| 150 | Reverse Integer | Math | Build reversed number digit by digit; check overflow |