Meta Interview Morning Refresher

Easy + Medium only (110 questions)

Total 110 Easy 34 Medium 76

Review pattern -> 5-step flow -> complexity

Open Listen Mode (Chrome Reading Mode friendly)

Binary Search & Selection (7)

LC Problem Diff Pattern 5-Step Flow Time Space LeetCode
LC 278 First Bad Version Easy Leftmost Binary Search
  1. Clarify: Is isBadVersion() expensive? (Yes — minimizing calls is the entire point)
  2. Pattern: Leftmost Binary Search
  3. Core: Versions form a monotonic boolean array: [GOOD...GOOD, BAD...BAD].
  4. Verify: Input: n=5, bad=4
  5. Trap: Integer overflow: mid=(lo+hi)//2 overflows when lo+hi approaches INT_MAX.
O(log n) O(1)
LC 33 Search in Rotated Sorted Array Medium Binary Search
  1. Clarify: Are all elements distinct? (follow-up: LC 81 with duplicates)
  2. Pattern: Binary Search
  3. Core: Even in a rotated array, ONE of the two halves around mid is ALWAYS normally sorted.
  4. Verify: Input: nums=[4,5,6,7,0,1,2], target=0 → Output: 4
  5. Trap: Using strict < instead of <= in nums[lo] <= nums[mid].
O(log n) O(1)
LC 34 Find First and Last Position of Element in Sorted Array Medium Binary Search ×2
  1. Clarify: Array sorted non-decreasing — confirmed?
  2. Pattern: Binary Search ×2
  3. Core: Run binary search TWICE — once biased LEFT (find first occurrence), once biased RIGHT (find last).
  4. Verify: Input: nums=[5,7,7,8,8,10], target=8 → Output: [3,4]
  5. Trap: Trying to solve in ONE pass — almost always introduces subtle bugs.
O(log n) O(1)
LC 162 Find Peak Element Medium Binary Search on Answer
  1. Clarify: Is there guaranteed to be at least one peak? (Yes — boundaries are -∞)
  2. Pattern: Binary Search on Answer
  3. Core: At any midpoint, if nums[mid] < nums[mid+1], the slope goes UP — a peak MUST exist to the right.
  4. Verify: Input: nums=[1,2,3,1] → Output: 2 (nums[2]=3)
  5. Trap: Writing while lo<=hi with hi=mid-1.
O(log n) O(1)
LC 215 Kth Largest Element in an Array Medium Quickselect (or Min-Heap)
  1. Clarify: k is 1-indexed largest (k=1 means max)?
  2. Pattern: Quickselect (or Min-Heap)
  3. Core: Quickselect partitions like Quicksort but only recurses/iterates into one side containing the target index.
  4. Verify: Input: nums=[3,2,1,5,6,4], k=2 -> 5
  5. Trap: Sorting entire array gives O(n log n), which is accepted but not optimal.
Average O(n), worst O(n²) O(1)
LC 378 Kth Smallest Element in a Sorted Matrix Medium Binary Search on Value Space
  1. Clarify: Rows and columns both sorted ascending?
  2. Pattern: Binary Search on Value Space
  3. Core: Binary search over the VALUE range `[minVal, maxVal]`, not indices.
  4. Verify: Input: matrix=[[1,5,9],[10,11,13],[12,13,15]], k=8 -> 13
  5. Trap: Flattening then sorting costs O(n² log n).
O(n log(maxVal-minVal)) O(1)
LC 528 Random Pick with Weight Medium Prefix Sum + Binary Search
  1. Clarify: Weights are positive integers?
  2. Pattern: Prefix Sum + Binary Search
  3. Core: Build prefix sums so each index owns an interval of total weight.
  4. Verify: Input: w=[1,3]
  5. Trap: Off-by-one in random target range is common.
Init O(n), pick O(log n) O(n)

Graphs & Trees (28)

LC Problem Diff Pattern 5-Step Flow Time Space LeetCode
LC 67 Add Binary Easy Simultaneous Traversal + Carry
  1. Clarify: Inputs contain only '0' and '1'?
  2. Pattern: Simultaneous Traversal + Carry
  3. Core: Identical structure to Add Two Numbers.
  4. Verify: Input: a="11", b="1" → Output: "100"
  5. Trap: Building result with string concatenation inside the loop: result = str(digit) + result.
O(max(m,n)) O(max(m,n))
LC 100 Same Tree Easy DFS (Parallel Traversal)
  1. Clarify: Are both trees possibly empty? (Yes)
  2. Pattern: DFS (Parallel Traversal)
  3. Core: Traverse both trees in lockstep.
  4. Verify: Input: p=[1,2,3], q=[1,2,3] -> true
  5. Trap: Checking only in-order traversals or value multisets.
O(n) O(h)
LC 110 Balanced Binary Tree Easy Post-Order DFS + Height Check
  1. Clarify: Empty tree is balanced? (Yes)
  2. Pattern: Post-Order DFS + Height Check
  3. Core: Use post-order DFS so each node gets left/right heights from children first.
  4. Verify: Input: root=[3,9,20,null,null,15,7] -> true
  5. Trap: Computing height separately for each node (`isBalanced` calls `height` repeatedly) causes O(n^2) in skewed trees.
O(n) O(h)
LC 257 Binary Tree Paths Easy DFS + Path Building
  1. Clarify: Return root-to-leaf only (not every path)?
  2. Pattern: DFS + Path Building
  3. Core: Classic DFS.
  4. Verify: Input: root=[1,2,3,null,5]
  5. Trap: Using one shared string without backtracking correctly.
O(n) O(h)
LC 270 Closest Binary Search Tree Value Easy BST Guided Traversal
  1. Clarify: Return node value (not node reference)?
  2. Pattern: BST Guided Traversal
  3. Core: Use BST ordering to discard half the tree each step.
  4. Verify: Input: root=[4,2,5,1,3], target=3.714286 -> 4
  5. Trap: Doing full DFS/BFS over all nodes (O(n)) and ignoring BST property.
O(h) O(1)
LC 339 Nested List Weight Sum Easy DFS/BFS with Depth Tracking
  1. Clarify: Root depth starts at 1?
  2. Pattern: DFS/BFS with Depth Tracking
  3. Core: Traverse all elements while carrying current depth.
  4. Verify: Input: nestedList=[[1,1],2,[1,1]]
  5. Trap: Forgetting to increment depth when descending into child lists causes underweighted sums.
O(n) O(d)
LC 543 Diameter of Binary Tree Easy DFS Height + Global Max
  1. Clarify: Diameter measured in edges (not nodes)?
  2. Pattern: DFS Height + Global Max
  3. Core: At each node, candidate diameter is leftHeight + rightHeight.
  4. Verify: Input: [1,2,3,4,5]
  5. Trap: Returning `best` from recursion instead of node height.
O(n) O(h)
LC 938 Range Sum of BST Easy DFS + BST Pruning
  1. Clarify: Range is inclusive [low, high]?
  2. Pattern: DFS + BST Pruning
  3. Core: DFS with pruning: if node value is smaller than low, skip entire left subtree; if larger than high, skip entire right subtree.
  4. Verify: Input: root=[10,5,15,3,7,null,18], low=7, high=15 -> 32
  5. Trap: Ignoring BST property and doing plain full-tree DFS every time.
O(n) worst-case, O(m) average with pruning O(h)
LC 2 Add Two Numbers Medium Simultaneous Traversal + Carry
  1. Clarify: Digits stored in REVERSE order — head is the ones place? (This is the gift — no reversal needed)
  2. Pattern: Simultaneous Traversal + Carry
  3. Core: Simulate third-grade addition: add digit by digit from right to left, carrying overflow.
  4. Verify: Input: l1=2→4→3 (342), l2=5→6→4 (465)
  5. Trap: Loop condition 'while l1 OR l2' without the third condition 'OR carry != 0'.
O(max(m,n)) O(max(m,n))
LC 98 Validate Binary Search Tree Medium DFS + Range Propagation
  1. Clarify: Strictly less than or can equal values exist?
  2. Pattern: DFS + Range Propagation
  3. Core: Naive mistake: only check local parent-child relationship.
  4. Verify: Input: 2 Output: true
  5. Trap: Using only local parent-child check (node.left.val < node.val).
O(n) O(h)
LC 114 Flatten Binary Tree to Linked List Medium Morris Traversal
  1. Clarify: In-place only — confirmed?
  2. Pattern: Morris Traversal
  3. Core: For each node: find the RIGHTMOST node of its left subtree (the pre-order predecessor).
  4. Verify: Input: 1 Output: 1→2→3→4→5→6
  5. Trap: Recursive solutions get pointer order wrong under pressure — you move a pointer before saving a reference and lose part of the tree.
O(n) O(1)
LC 129 Sum Root to Leaf Numbers Medium DFS Accumulating Path Value
  1. Clarify: Node values are single digits 0..9?
  2. Pattern: DFS Accumulating Path Value
  3. Core: Carry a running number while traversing: `curr = curr*10 + node.val`.
  4. Verify: Input: root=[1,2,3]
  5. Trap: Collecting full path strings/arrays first and converting later adds unnecessary overhead.
O(n) O(h)
LC 133 Clone Graph Medium BFS + HashMap
  1. Clarify: Can graph have cycles? (Yes — visited map prevents infinite loops)
  2. Pattern: BFS + HashMap
  3. Core: BFS/DFS traversal + HashMap {original → clone}.
  4. Verify: Input: adjList=[[2,4],[1,3],[2,4],[1,3]]
  5. Trap: Adding neighbors before checking visited — creates duplicate clone nodes for the same original.
O(V+E) O(V)
LC 173 Binary Search Tree Iterator Medium Controlled In-Order Traversal
  1. Clarify: Average O(1) for next() — not worst-case?
  2. Pattern: Controlled In-Order Traversal
  3. Core: Simulate in-order traversal LAZILY — only compute the next element when next() is called.
  4. Verify: BSTIterator(root=[7,3,15,null,null,9,20])
  5. Trap: Claiming O(1) worst-case instead of AMORTIZED O(1).
Amortized O(1) O(h)
LC 199 Binary Tree Right Side View Medium BFS Level-Order
  1. Clarify: Right side = last visible node at each depth level?
  2. Pattern: BFS Level-Order
  3. Core: BFS level-by-level.
  4. Verify: Input: 1 Output: [1,3,4]
  5. Trap: DFS left-first and taking last at each depth gets right/left priority backwards.
O(n) O(w)
LC 200 Number of Islands Medium BFS Flood Fill
  1. Clarify: 4-directional connectivity only (no diagonals)?
  2. Pattern: BFS Flood Fill
  3. Core: Every time you find an unvisited '1', you've found a new island — increment counter.
  4. Verify: Input:
  5. Trap: Marking visited AFTER dequeuing instead of ON ENQUEUE.
O(m×n) O(min(m,n))
LC 207 Course Schedule Medium Topological Sort (Kahn)
  1. Clarify: Is prerequisite pair [a,b] meaning b -> a edge?
  2. Pattern: Topological Sort (Kahn)
  3. Core: A course plan is possible iff the prerequisite graph is acyclic.
  4. Verify: Input: numCourses=2, prerequisites=[[1,0]]
  5. Trap: Only running BFS/DFS from course 0 misses disconnected components.
O(V+E) O(V+E)
LC 210 Course Schedule II Medium Topological Sort (Kahn, Order Construction)
  1. Clarify: Any valid topological order accepted?
  2. Pattern: Topological Sort (Kahn, Order Construction)
  3. Core: Same graph as LC 207, but instead of counting only, record dequeue order during Kahn's algorithm.
  4. Verify: Input: numCourses=2, prerequisites=[[1,0]]
  5. Trap: Using DFS without proper cycle-state tracking can return invalid partial orders.
O(V+E) O(V+E)
LC 211 Design Add and Search Words Data Structure Medium Trie + DFS Wildcard
  1. Clarify: '.' matches any SINGLE letter — confirmed?
  2. Pattern: Trie + DFS Wildcard
  3. Core: Trie for prefix-matching structure.
  4. Verify: WordDictionary wd
  5. Trap: Using a flat list for storage and doing regex scan for search — gives O(n×m) per search where n=words stored.
O(m) add, O(26^m) search worst O(total chars)
LC 236 Lowest Common Ancestor of a Binary Tree Medium DFS Post-Order
  1. Clarify: Are p and q guaranteed to exist? (Logic changes if not)
  2. Pattern: DFS Post-Order
  3. Core: Post-order DFS.
  4. Verify: Input: tree=[3,5,1,6,2,0,8,null,null,7,4], p=5, q=1
  5. Trap: Early-terminating when finding p without checking its subtree for q.
O(n) O(h)
LC 314 Binary Tree Vertical Order Traversal Medium BFS + Column Indexing
  1. Clarify: Within same row/column, should order follow BFS left-to-right?
  2. Pattern: BFS + Column Indexing
  3. Core: Use BFS with (node, column).
  4. Verify: Input: [3,9,20,null,null,15,7]
  5. Trap: Using DFS without row tracking can break required ordering for nodes sharing the same column.
O(n) O(n)
LC 426 Convert Binary Search Tree to Sorted Doubly Linked List Medium In-Order Traversal + Pointer Stitching
  1. Clarify: Output must be circular?
  2. Pattern: In-Order Traversal + Pointer Stitching
  3. Core: In-order traversal visits nodes in sorted order.
  4. Verify: Input: [4,2,5,1,3]
  5. Trap: Forgetting final head-tail linking.
O(n) O(h)
LC 545 Boundary of Binary Tree Medium Tree Traversal (Left Boundary + Leaves + Right Boundary)
  1. Clarify: Boundary is anti-clockwise and starts with root?
  2. Pattern: Tree Traversal (Left Boundary + Leaves + Right Boundary)
  3. Core: Build answer in three non-overlapping passes: left boundary (top-down, skip leaves), leaves (full DFS), right boundary (top-down into temp, skip leaves, then reverse).
  4. Verify: Input: root=[1,null,2,3,4]
  5. Trap: Including leaves in left/right boundary loops duplicates them when leaf pass runs.
O(n) O(h)
LC 721 Accounts Merge Medium Union-Find + Email Graph
  1. Clarify: Same name does not guarantee same person?
  2. Pattern: Union-Find + Email Graph
  3. Core: Union emails that appear in the same account.
  4. Verify: Input:
  5. Trap: Merging by name alone.
O(N alpha(N) + E log E) O(E)
LC 785 Is Graph Bipartite? Medium BFS 2-Coloring
  1. Clarify: Can graph be disconnected? (Yes — MUST check ALL components)
  2. Pattern: BFS 2-Coloring
  3. Core: Try to 2-color the graph — color every node RED or BLUE such that no two adjacent nodes share a color.
  4. Verify: Input: graph=[[1,2,3],[0,2],[0,1,3],[0,2]]
  5. Trap: Not handling disconnected graphs.
O(V+E) O(V)
LC 863 All Nodes Distance K in Binary Tree Medium Tree to Undirected Graph + BFS
  1. Clarify: Distance is number of edges?
  2. Pattern: Tree to Undirected Graph + BFS
  3. Core: Tree nodes only have child pointers, but distance-k search needs moving both downward and upward.
  4. Verify: Input: root=[3,5,1,6,2,0,8,null,null,7,4], target=5, k=2
  5. Trap: Forgetting a visited set causes infinite revisits between child and parent pointers after adding parent edges.
O(n) O(n)
LC 1091 Shortest Path in Binary Matrix Medium 8-Direction BFS on Grid
  1. Clarify: Moves allowed in all 8 directions (including diagonals)?
  2. Pattern: 8-Direction BFS on Grid
  3. Core: Treat each clear cell as an unweighted graph node and run BFS from (0,0).
  4. Verify: Input: grid=[[0,1],[1,0]] -> 2
  5. Trap: Using DFS/greedy can miss the shortest path in an unweighted graph.
O(n^2) O(n^2)
LC 1382 Balance a Binary Search Tree Medium In-Order Traversal + Rebuild from Sorted Array
  1. Clarify: Need to preserve original node objects, or can create new nodes? (Either accepted on LeetCode)
  2. Pattern: In-Order Traversal + Rebuild from Sorted Array
  3. Core: In-order traversal of BST gives sorted values.
  4. Verify: Input: root=[1,null,2,null,3,null,4,null,null]
  5. Trap: Trying local AVL-style rotations from an arbitrary unbalanced BST is complex and error-prone for interviews.
O(n) O(n)

Sliding Window & Two Pointers (19)

LC Problem Diff Pattern 5-Step Flow Time Space LeetCode
LC 26 Remove Duplicates from Sorted Array Easy Two Pointers (Write Index)
  1. Clarify: Array is sorted non-decreasing?
  2. Pattern: Two Pointers (Write Index)
  3. Core: Maintain write pointer for next unique slot.
  4. Verify: Input: nums=[1,1,2]
  5. Trap: Comparing against nums[write-1] after overwrites without understanding invariants can cause subtle mistakes.
O(n) O(1)
LC 88 Merge Sorted Array Easy Two Pointers from End
  1. Clarify: nums1 has enough trailing space?
  2. Pattern: Two Pointers from End
  3. Core: Fill nums1 from the back.
  4. Verify: Input: nums1=[1,2,3,0,0,0], m=3, nums2=[2,5,6], n=3
  5. Trap: Merging from the front overwrites unread values in nums1.
O(m+n) O(1)
LC 125 Valid Palindrome Easy Two Pointers + Inline Filter
  1. Clarify: Ignore case and non-alphanumeric — confirmed?
  2. Pattern: Two Pointers + Inline Filter
  3. Core: Two pointers from both ends.
  4. Verify: Input: s="A man, a plan, a canal: Panama" → true
  5. Trap: Creating a cleaned string first (filter + lowercase) then checking palindrome.
O(n) O(1)
LC 283 Move Zeroes Easy Two Pointers (Read/Write)
  1. Clarify: In-place — confirmed?
  2. Pattern: Two Pointers (Read/Write)
  3. Core: slow pointer marks the next write position for non-zero elements.
  4. Verify: Input: nums=[0,1,0,3,12] → Output: [1,3,12,0,0]
  5. Trap: Using the swap variant without understanding its trade-off.
O(n) O(1)
LC 408 Valid Word Abbreviation Easy Two Pointers + Number Parsing
  1. Clarify: Are leading zeros in a number allowed? (No)
  2. Pattern: Two Pointers + Number Parsing
  3. Core: Use two pointers: `i` for `word`, `j` for `abbr`.
  4. Verify: Input: word="internationalization", abbr="i12iz4n" -> true
  5. Trap: Parsing only one digit at a time instead of full numbers.
O(n+m) O(1)
LC 680 Valid Palindrome II Easy Two Pointers + One Skip Allowance
  1. Clarify: At most one deletion — zero deletions (already palindrome) also returns true?
  2. Pattern: Two Pointers + One Skip Allowance
  3. Core: Two-pointer palindrome check.
  4. Verify: Input: s="aba" → true (already palindrome)
  5. Trap: Allowing recursive skips inside isPalindrome.
O(n) O(1)
LC 3 Longest Substring Without Repeating Characters Medium Sliding Window + HashMap
  1. Clarify: Return the length or the substring itself?
  2. Pattern: Sliding Window + HashMap
  3. Core: Sliding window [left, right].
  4. Verify: Input: s="abcabcbb" → Output: 3 ("abc")
  5. Trap: Missing the condition map[c] >= left.
O(n) O(min(n, alphabet))
LC 11 Container With Most Water Medium Two Pointers (Greedy)
  1. Clarify: Return only the max area (not the indices)?
  2. Pattern: Two Pointers (Greedy)
  3. Core: Use two pointers at both ends.
  4. Verify: Input: height=[1,8,6,2,5,4,8,3,7] -> 49
  5. Trap: Brute force O(n^2) checks all pairs and times out at larger constraints.
O(n) O(1)
LC 15 3Sum Medium Sort + Two Pointers
  1. Clarify: Distinct indices but values can repeat?
  2. Pattern: Sort + Two Pointers
  3. Core: Sort the array.
  4. Verify: Input: nums=[-1,0,1,2,-1,-4]
  5. Trap: Duplicate skipping at the wrong level.
O(n²) O(1)
LC 31 Next Permutation Medium Pivot + Reverse Suffix
  1. Clarify: Must modify in-place?
  2. Pattern: Pivot + Reverse Suffix
  3. Core: Find rightmost pivot `i` where nums[i] < nums[i+1].
  4. Verify: Input: [1,2,3] -> [1,3,2]
  5. Trap: Sorting the suffix instead of reversing it.
O(n) O(1)
LC 56 Merge Intervals Medium Sort + Linear Scan
  1. Clarify: Sort by start time first?
  2. Pattern: Sort + Linear Scan
  3. Core: Sort by start.
  4. Verify: Input: intervals=[[1,3],[2,6],[8,10],[15,18]]
  5. Trap: Writing last.end = curr.end instead of max(last.end, curr.end).
O(n log n) O(n)
LC 57 Insert Interval Medium Single Pass Merge over Sorted Intervals
  1. Clarify: Input intervals are already sorted and mutually non-overlapping?
  2. Pattern: Single Pass Merge over Sorted Intervals
  3. Core: Three phases in one pass: (1) append all intervals ending before newInterval starts, (2) merge all overlapping intervals into newInterval, (3) append the rest.
  4. Verify: Input: intervals=[[1,3],[6,9]], newInterval=[2,5]
  5. Trap: Using strict overlap check `intervals[i][0] < newInterval[1]` misses touching boundaries like [1,2] and [2,3], which should merge for closed intervals.
O(n) O(n)
LC 161 One Edit Distance Medium Two Pointers + Single Mismatch Budget
  1. Clarify: Exactly one edit (not zero)?
  2. Pattern: Two Pointers + Single Mismatch Budget
  3. Core: Scan until first mismatch.
  4. Verify: Input: s="ab", t="acb" -> true
  5. Trap: Returning true when strings are identical.
O(n) O(1)
LC 340 Longest Substring with At Most K Distinct Characters Medium Sliding Window + Frequency Map
  1. Clarify: Return length or the substring?
  2. Pattern: Sliding Window + Frequency Map
  3. Core: Variable sliding window.
  4. Verify: Input: s="eceba", k=2 → Output: 3 ("ece")
  5. Trap: Not deleting the key from the map when count reaches 0.
O(n) O(k)
LC 438 Find All Anagrams in a String Medium Sliding Window + Frequency Map
  1. Clarify: Return starting indices of all anagram substrings?
  2. Pattern: Sliding Window + Frequency Map
  3. Core: Fixed-size sliding window of exactly len(p).
  4. Verify: Input: s="cbaebabacd", p="abc" → Output: [0,6]
  5. Trap: Comparing full frequency maps each window step instead of using the matched counter.
O(s+p) O(1)
LC 567 Permutation in String Medium Sliding Window + Frequency Map
  1. Clarify: A permutation of s1 is a substring of s2 — confirmed? (Same as checking for any anagram)
  2. Pattern: Sliding Window + Frequency Map
  3. Core: Structurally identical to Find All Anagrams — this is the same problem with a boolean return instead of collecting all indices.
  4. Verify: Input: s1="ab", s2="eidbaooo" → Output: true ("ba" at idx 3)
  5. Trap: Treating this as a unique problem and re-deriving from scratch.
O(s1+s2) O(1)
LC 986 Interval List Intersections Medium Two Pointers on Sorted Intervals
  1. Clarify: Closed intervals [a,b] — endpoints inclusive? (Yes: [2,3] and [3,4] intersect at [3,3])
  2. Pattern: Two Pointers on Sorted Intervals
  3. Core: Two pointers, one per list.
  4. Verify: A=[[0,2],[5,10],[13,23],[24,25]]
  5. Trap: Over-engineering with elaborate if-else for all overlap cases (A before B, B before A, A contains B, nested...).
O(m+n) O(m+n)
LC 1868 Product of Two Run-Length Encoded Arrays Medium Two Pointers over RLE Runs
  1. Clarify: Each pair is [value, frequency]?
  2. Pattern: Two Pointers over RLE Runs
  3. Core: Walk both encoded arrays with two pointers.
  4. Verify: Input: encoded1=[[1,3],[2,3]], encoded2=[[6,3],[3,3]]
  5. Trap: Decoding both arrays first can explode memory/time when frequencies are large.
O(n+m) O(1) extra (excluding output)
LC 3634 Minimum Removals to Balance Array Medium Sort + Sliding Window (Two Pointers)
  1. Clarify: Can we remove elements from any positions (not necessarily contiguous)?
  2. Pattern: Sort + Sliding Window (Two Pointers)
  3. Core: After sorting, keeping a balanced subset is equivalent to finding the longest window `[l..r]` where `nums[r] <= k * nums[l]`.
  4. Verify: Input: nums=[2,1,5,6], k=3 -> 1
  5. Trap: Trying unsorted greedy removals by local min/max updates often fails.
O(n log n) O(1) extra (or O(log n) sort stack)

Backtracking (7)

LC Problem Diff Pattern 5-Step Flow Time Space LeetCode
LC 17 Letter Combinations of a Phone Number Medium Backtracking
  1. Clarify: Return [] not [''] for empty input — confirmed?
  2. Pattern: Backtracking
  3. Core: Decision tree — each level is one digit.
  4. Verify: Input: digits="23"
  5. Trap: Returning [''] instead of [] for empty input.
O(4ⁿ×n) O(n)
LC 22 Generate Parentheses Medium Backtracking with Valid Prefix Pruning
  1. Clarify: Return only valid strings?
  2. Pattern: Backtracking with Valid Prefix Pruning
  3. Core: Build candidates character-by-character while tracking how many opening and closing brackets are used.
  4. Verify: Input: n=3
  5. Trap: Generating all 2^(2n) strings and filtering valid ones is too slow.
O(Cn×n) O(n)
LC 46 Permutations Medium Backtracking
  1. Clarify: All integers distinct? (Duplicates → LC 47)
  2. Pattern: Backtracking
  3. Core: At each position in the permutation, choose one unused number from the remaining pool.
  4. Verify: Input: nums=[1,2,3]
  5. Trap: Not copying path before appending to result.
O(n!×n) O(n)
LC 47 Permutations II Medium Backtracking + Dedup
  1. Clarify: Must deduplicate output — confirmed?
  2. Pattern: Backtracking + Dedup
  3. Core: Sort first.
  4. Verify: Input: nums=[1,1,2]
  5. Trap: The dedup condition is NOT used[i-1].
O(n!×n) O(n)
LC 77 Combinations Medium Backtracking (Choose k)
  1. Clarify: Numbers are from 1..n inclusive?
  2. Pattern: Backtracking (Choose k)
  3. Core: Backtrack with a start pointer so each number is used at most once and order is naturally increasing.
  4. Verify: Input: n=4, k=2
  5. Trap: Using permutations template (loop from 1 every time) generates duplicates like [1,2] and [2,1].
O(C(n,k)×k) O(k)
LC 78 Subsets Medium Backtracking
  1. Clarify: All elements unique? (Duplicates → LC 90)
  2. Pattern: Backtracking
  3. Core: At each index, make a binary decision: INCLUDE or EXCLUDE.
  4. Verify: Input: nums=[1,2,3]
  5. Trap: Adding to result only at depth==n (copying Permutations template).
O(2ⁿ×n) O(n)
LC 247 Strobogrammatic Number II Medium Backtracking / Construct from Center
  1. Clarify: Can result include numbers with leading zero? (Only allowed when n==1)
  2. Pattern: Backtracking / Construct from Center
  3. Core: Build from the center outward using valid mirrored pairs.
  4. Verify: Input: n=2
  5. Trap: Allowing '0...0' at the outermost layer for n>1.
O(5^(n/2)) O(5^(n/2))

DP & Prefix Sum (8)

LC Problem Diff Pattern 5-Step Flow Time Space LeetCode
LC 509 Fibonacci Number Easy DP (Rolling Variables)
  1. Clarify: n range? (usually 0..30 on LC)
  2. Pattern: DP (Rolling Variables)
  3. Core: Bottom-up DP with O(1) space: keep only the previous two Fibonacci values and iteratively build up to n.
  4. Verify: Input: n=2 -> 1
  5. Trap: Using plain recursion without memoization leads to exponential O(2^n) time due to repeated subproblems.
O(n) O(1)
LC 91 Decode Ways Medium 1D DP
  1. Clarify: '0' cannot start any valid encoding — confirmed?
  2. Pattern: 1D DP
  3. Core: dp[i] = number of ways to decode first i characters.
  4. Verify: Input: s="12" → Output: 2 ("AB"=1+2, "L"=12)
  5. Trap: Handling '0' incorrectly.
O(n) O(n)→O(1)
LC 139 Word Break Medium 1D DP
  1. Clarify: Can same word be reused? (Yes)
  2. Pattern: 1D DP
  3. Core: dp[i] = can first i chars be segmented.
  4. Verify: Input: s="leetcode", wordDict=["leet","code"] → true
  5. Trap: Using a list instead of HashSet for wordDict.
O(n²) O(n)
LC 304 Range Sum Query 2D - Immutable Medium 2D Prefix Sum
  1. Clarify: Multiple queries on same fixed matrix? (Preprocessing is the whole motivation)
  2. Pattern: 2D Prefix Sum
  3. Core: Build 2D prefix sum table.
  4. Verify: matrix=[[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]
  5. Trap: Getting inclusion-exclusion signs wrong.
O(1) query / O(mn) build O(m×n)
LC 322 Coin Change Medium 1D DP (Unbounded Knapsack Min Coins)
  1. Clarify: Unlimited reuse of each coin denomination?
  2. Pattern: 1D DP (Unbounded Knapsack Min Coins)
  3. Core: Let `dp[a]` be the minimum coins required for amount `a`.
  4. Verify: Input: coins=[1,2,5], amount=11 -> 3
  5. Trap: Confusing this with 'Coin Change II' (count ways).
O(amount × len(coins)) O(amount)
LC 523 Continuous Subarray Sum Medium Prefix Sum + Modulo HashMap
  1. Clarify: Subarray must have at least TWO elements?
  2. Pattern: Prefix Sum + Modulo HashMap
  3. Core: prefixSum[j] % k == prefixSum[i-1] % k means subarray nums[i..j] is divisible by k.
  4. Verify: Input: nums=[23,2,4,6,7], k=6 → true ([2,4] sums to 6)
  5. Trap: Two landmines: (1) Updating map when remainder already exists — must keep EARLIEST index to maximize subarray length.
O(n) O(min(n,k))
LC 560 Subarray Sum Equals K Medium Prefix Sum + HashMap
  1. Clarify: Count subarrays (not just existence)?
  2. Pattern: Prefix Sum + HashMap
  3. Core: prefixSum[j] - prefixSum[i] = k means subarray i+1..j sums to k.
  4. Verify: Input: nums=[1,1,1], k=2 → Output: 2
  5. Trap: Attempting sliding window.
O(n) O(n)
LC 1653 Minimum Deletions to Make String Balanced Medium One-Pass DP (Prefix b Count)
  1. Clarify: Only characters 'a' and 'b' appear?
  2. Pattern: One-Pass DP (Prefix b Count)
  3. Core: Scan left to right.
  4. Verify: Input: s="aababbab" -> 2
  5. Trap: Greedy deleting only current 'a' when conflict appears is not always optimal.
O(n) O(1)

Stack & Parsing (7)

LC Problem Diff Pattern 5-Step Flow Time Space LeetCode
LC 20 Valid Parentheses Easy Stack
  1. Clarify: Can string length be odd? (then immediately false)
  2. Pattern: Stack
  3. Core: Use a stack of opening brackets.
  4. Verify: Input: s="()" -> true
  5. Trap: Trying to validate by counting each bracket type independently (e.g., number of '(' equals ')').
O(n) O(n)
LC 496 Next Greater Element I Easy Monotonic Stack + HashMap
  1. Clarify: nums1 values are unique and subset of nums2?
  2. Pattern: Monotonic Stack + HashMap
  3. Core: Precompute next-greater for every value in nums2 using a decreasing monotonic stack.
  4. Verify: Input: nums1=[4,1,2], nums2=[1,3,4,2] -> [-1,3,-1]
  5. Trap: For each nums1 value, linearly scanning right in nums2 gives O(m*n).
O(n+m) O(n)
LC 8 String to Integer (atoi) Medium State Machine / Linear Parse
  1. Clarify: Skip leading whitespace?
  2. Pattern: State Machine / Linear Parse
  3. Core: Strict sequential state machine: (1) skip whitespace, (2) read sign, (3) read digits with pre-multiplication overflow check, (4) stop on first non-digit.
  4. Verify: Input: s="42" → Output: 42
  5. Trap: Checking overflow AFTER updating result — by then the value has already wrapped or been clamped incorrectly.
O(n) O(1)
LC 71 Simplify Path Medium Stack + Tokenization
  1. Clarify: Input path is absolute (starts with '/')?
  2. Pattern: Stack + Tokenization
  3. Core: Split by '/'.
  4. Verify: Input: path="/home/" -> "/home"
  5. Trap: Trying ad-hoc string replacements (like repeatedly replacing '/./' or '/../') misses edge cases with multiple slashes and root boundary behavior.
O(n) O(n)
LC 468 Validate IP Address Medium String Parsing + Case Analysis
  1. Clarify: IPv4: 4 decimal groups, 0-255, no leading zeros (except '0' itself)?
  2. Pattern: String Parsing + Case Analysis
  3. Core: Split on '.' for IPv4, ':' for IPv6.
  4. Verify: Input: "172.16.254.1" → "IPv4"
  5. Trap: Python's split('.') on '1.2.3.4.' produces ['1','2','3','4',''] — 5 parts.
O(1) O(1)
LC 636 Exclusive Time of Functions Medium Stack + Previous Timestamp
  1. Clarify: Logs are already sorted by timestamp?
  2. Pattern: Stack + Previous Timestamp
  3. Core: Use a stack of active function IDs and keep `prevTime`.
  4. Verify: Input:
  5. Trap: Forgetting that `end` timestamp is inclusive.
O(m) O(n)
LC 1249 Minimum Remove to Make Valid Parentheses Medium Stack + Mark Invalid Indices
  1. Clarify: Letters should remain in original relative order?
  2. Pattern: Stack + Mark Invalid Indices
  3. Core: Use a stack to track indices of unmatched '(' and a set to mark invalid indices.
  4. Verify: Input: s="lee(t(c)o)de)" -> "lee(t(c)o)de"
  5. Trap: Removing characters directly from the string during traversal causes index shifts and bugs.
O(n) O(n)

Hashing & Counting (12)

LC Problem Diff Pattern 5-Step Flow Time Space LeetCode
LC 1 Two Sum Easy HashMap (Complement Lookup)
  1. Clarify: Return indices, not values?
  2. Pattern: HashMap (Complement Lookup)
  3. Core: As you scan left to right, for each value x, you need target-x.
  4. Verify: Input: nums=[2,7,11,15], target=9 -> Output: [0,1]
  5. Trap: Sorting first and then using two pointers without preserving original indices.
O(n) O(n)
LC 217 Contains Duplicate Easy HashSet
  1. Clarify: Return boolean only?
  2. Pattern: HashSet
  3. Core: Track seen values in a HashSet.
  4. Verify: Input: nums=[1,2,3,1] -> true
  5. Trap: Sorting first and then checking neighbors gives O(n log n) and mutates input order.
O(n) O(n)
LC 219 Contains Duplicate II Easy HashMap (Last Seen Index)
  1. Clarify: Distance condition is index distance (abs(i-j))?
  2. Pattern: HashMap (Last Seen Index)
  3. Core: Track last seen index of each value in a HashMap.
  4. Verify: Input: nums=[1,2,3,1], k=3 -> true
  5. Trap: Forgetting to update `last[x]` when distance > k.
O(n) O(n)
LC 349 Intersection of Two Arrays Easy HashSet
  1. Clarify: Result elements must be unique (not duplicates)?
  2. Pattern: HashSet
  3. Core: Hash the smaller array into a set.
  4. Verify: Input: nums1=[1,2,2,1], nums2=[2,2] → Output: [2]
  5. Trap: Not asking if arrays are sorted.
O(n+m) O(min(n,m))
LC 350 Intersection of Two Arrays II Easy HashMap (Frequency)
  1. Clarify: Preserve duplicate counts — confirmed?
  2. Pattern: HashMap (Frequency)
  3. Core: Frequency map from smaller array.
  4. Verify: Input: nums1=[1,2,2,1], nums2=[2,2] → Output: [2,2]
  5. Trap: Not knowing the follow-up: 'What if arrays are too large for memory?' Answer: sort both, stream from disk, use two-pointer merge — O(1) in-memory.
O(n+m) O(min(n,m))
LC 953 Verifying an Alien Dictionary Easy Custom Comparator
  1. Clarify: Need pairwise check across adjacent words only?
  2. Pattern: Custom Comparator
  3. Core: Build rank map from alien order and compare each adjacent pair by first differing character; handle prefix invalid case.
  4. Verify: Input: words=["hello","leetcode"], order="hlabcdefgijkmnopqrstuvwxyz"
  5. Trap: Ignoring prefix invalid case (`"abc"` before `"ab"`).
O(total chars) O(1)
LC 49 Group Anagrams Medium HashMap + Canonical Key
  1. Clarify: Strings guaranteed lowercase? (Yes in LC)
  2. Pattern: HashMap + Canonical Key
  3. Core: Two strings are anagrams iff their sorted characters are identical.
  4. Verify: Input: strs=["eat","tea","tan","ate","nat","bat"]
  5. Trap: Not knowing the O(k) frequency tuple optimization.
O(n×k log k) O(n×k)
LC 138 Copy List with Random Pointer Medium HashMap or Interleaving
  1. Clarify: Random can point to any node OR be null — confirmed?
  2. Pattern: HashMap or Interleaving
  3. Core: HashMap {original → clone} serves dual purpose: visited set (prevents infinite loops) AND O(1) retrieval of any node's clone when wiring random pointers.
  4. Verify: Input: [[7,null],[13,0],[11,4],[10,2],[1,0]]
  5. Trap: In the interleave approach, Step 3 MUST restore the original list's next pointers (curr.next = curr.next.next).
O(n) O(n) or O(1)
LC 146 LRU Cache Medium HashMap + Doubly Linked List
  1. Clarify: get and put both must be O(1) — confirmed?
  2. Pattern: HashMap + Doubly Linked List
  3. Core: Need O(1) key lookup AND O(1) eviction of LRU item.
  4. Verify: LRUCache(capacity=2)
  5. Trap: Forgetting to delete the evicted key from the HashMap.
O(1) get and put O(capacity)
LC 347 Top K Frequent Elements Medium HashMap + Bucket Sort (or Min-Heap)
  1. Clarify: Any order in output accepted?
  2. Pattern: HashMap + Bucket Sort (or Min-Heap)
  3. Core: Count frequencies with a HashMap, then retrieve highest frequencies efficiently.
  4. Verify: Input: nums=[1,1,1,2,2,3], k=2 -> [1,2]
  5. Trap: Sorting all frequency pairs is O(m log m) where m is unique count, which may still pass but misses the expected linear-time follow-up.
O(n) O(n)
LC 791 Custom Sort String Medium Frequency Count + Custom Order
  1. Clarify: Are all characters lowercase English letters?
  2. Pattern: Frequency Count + Custom Order
  3. Core: Count frequency of characters in `s`.
  4. Verify: Input: order="cba", s="abcd" -> "cbad"
  5. Trap: Sorting `s` with a custom comparator works but is O(n log n).
O(|order| + |s|) O(1)
LC 3713 Longest Balanced Substring I Medium Enumeration + Frequency Counting
  1. Clarify: Substring must be contiguous? (Yes)
  2. Pattern: Enumeration + Frequency Counting
  3. Core: Fix start index `i` and expand end index `j`.
  4. Verify: Input: s="abbac" -> 4 ("abba")
  5. Trap: Trying a standard shrinking sliding window fails because the balanced condition is not monotonic as the right boundary grows.
O(n^2) O(1)

Design & Data Structures (1)

LC Problem Diff Pattern 5-Step Flow Time Space LeetCode
LC 346 Moving Average from Data Stream Easy Queue + Running Sum
  1. Clarify: Window size fixed at construction?
  2. Pattern: Queue + Running Sum
  3. Core: Maintain a queue of current window values and a running sum.
  4. Verify: MovingAverage(3)
  5. Trap: Recomputing sum of the whole queue on every `next` call leads to O(size) per operation.
O(1) per next O(size)

Greedy / Math / Bit / Misc (21)

LC Problem Diff Pattern 5-Step Flow Time Space LeetCode
LC 9 Palindrome Number Easy Math (Reverse Half)
  1. Clarify: Negative numbers are not palindromes?
  2. Pattern: Math (Reverse Half)
  3. Core: Do NOT reverse the whole number.
  4. Verify: Input: x=121 -> true
  5. Trap: Reversing the entire integer can overflow in fixed-width languages and does unnecessary work.
O(log10 n) O(1)
LC 13 Roman to Integer Easy Left-to-Right with Subtractive Rule
  1. Clarify: Input guaranteed valid Roman numeral?
  2. Pattern: Left-to-Right with Subtractive Rule
  3. Core: If current symbol is smaller than next, subtract it; otherwise add it.
  4. Verify: Input: "III" -> 3
  5. Trap: Attempting many special-case if blocks for each subtractive pair.
O(n) O(1)
LC 21 Merge Two Sorted Lists Easy Two Pointer Merge + Dummy Head
  1. Clarify: Both lists sorted non-decreasing — confirmed?
  2. Pattern: Two Pointer Merge + Dummy Head
  3. Core: Classic merge step from merge sort.
  4. Verify: Input: l1=1→2→4, l2=1→3→4
  5. Trap: Using the recursive solution without flagging its O(m+n) stack cost.
O(m+n) O(1)
LC 121 Best Time to Buy and Sell Stock Easy Greedy Single Pass
  1. Clarify: At most ONE transaction (one buy + one sell)?
  2. Pattern: Greedy Single Pass
  3. Core: Track the minimum price seen so far.
  4. Verify: Input: prices=[7,1,5,3,6,4] → Output: 5 (buy@1, sell@6)
  5. Trap: Not knowing the follow-up family.
O(n) O(1)
LC 157 Read N Characters Given Read4 Easy Buffer Management
  1. Clarify: read4 returns how many chars actually read (≤4)?
  2. Pattern: Buffer Management
  3. Core: Repeatedly call read4 into a temp 4-char buffer.
  4. Verify: File: "abcdefgh" (8 chars)
  5. Trap: Not capping the copy at n-totalRead.
O(n) O(1)
LC 231 Power of Two Easy Bit Manipulation
  1. Clarify: Should n<=0 return false?
  2. Pattern: Bit Manipulation
  3. Core: A positive power of two has exactly one bit set in binary.
  4. Verify: Input: n=1 -> true (2^0)
  5. Trap: Forgetting `n > 0` check.
O(1) O(1)
LC 412 Fizz Buzz Easy Simulation + Modulo
  1. Clarify: Output should be array of strings?
  2. Pattern: Simulation + Modulo
  3. Core: Direct simulation from 1 to n with ordered divisibility checks.
  4. Verify: Input: n=3 -> ["1","2","Fizz"]
  5. Trap: Checking `%3` before `%15` and `%5` before `%15` causes multiples of 15 to be labeled incorrectly as just "Fizz" or "Buzz".
O(n) O(n)
LC 824 Goat Latin Easy String Simulation
  1. Clarify: Words are separated by single spaces?
  2. Pattern: String Simulation
  3. Core: Process words left to right.
  4. Verify: Input: "I speak Goat Latin"
  5. Trap: Rebuilding the 'a' suffix from scratch each word with a nested loop can accidentally become O(n^2) in word count.
O(total chars) O(total chars)
LC 1929 Concatenation of Array Easy Array Construction
  1. Clarify: Return a new array (not modify in-place)?
  2. Pattern: Array Construction
  3. Core: Allocate result of size 2n and fill both halves in one pass.
  4. Verify: Input: nums=[1,2,1] -> [1,2,1,1,2,1]
  5. Trap: Using nested loops or repeated appends with expensive reallocation.
O(n) O(n)
LC 5 Longest Palindromic Substring Medium Expand Around Center
  1. Clarify: Return the substring or just its length?
  2. Pattern: Expand Around Center
  3. Core: Every palindrome has a CENTER.
  4. Verify: Input: s="babad" → Output: "bab" (or "aba", both valid)
  5. Trap: Forgetting even-length centers.
O(n²) O(1)
LC 29 Divide Two Integers Medium Bit Manipulation
  1. Clarify: Can we use *, /, % operators? (No — entire point)
  2. Pattern: Bit Manipulation
  3. Core: You can't divide — so fake it with bit shifts.
  4. Verify: Input: dividend=15, divisor=3 → Output: 5
  5. Trap: Nearly every candidate forgets INT_MIN ÷ -1.
O(log²n) O(1)
LC 43 Multiply Strings Medium Grade-School Multiplication
  1. Clarify: Can we use built-in big integer multiplication? (No — simulate manually)
  2. Pattern: Grade-School Multiplication
  3. Core: num1[i] × num2[j] contributes to positions [i+j] and [i+j+1] in the result array (0-indexed from left, MSB first).
  4. Verify: Input: num1="2", num2="3" → Output: "6"
  5. Trap: Propagating carries inside the inner multiplication loop instead of after.
O(m×n) O(m+n)
LC 45 Jump Game II Medium Greedy Layer Expansion
  1. Clarify: Need minimum jump count only, not the actual path?
  2. Pattern: Greedy Layer Expansion
  3. Core: Scan once using greedy ranges, like BFS levels over indices.
  4. Verify: Input: nums=[2,3,1,1,4] -> 2
  5. Trap: Using O(n^2) DP (`dp[i]=min(dp[j]+1)`) is correct but too slow for large inputs.
O(n) O(1)
LC 50 Pow(x, n) Medium Fast Exponentiation
  1. Clarify: Can n be negative? (x^-n = 1/x^n)
  2. Pattern: Fast Exponentiation
  3. Core: x^8 = (x^4)² = ((x^2)²)².
  4. Verify: Input: x=2.00000, n=10 → Output: 1024.00000
  5. Trap: Not casting n to long before negating.
O(log n) O(log n)
LC 55 Jump Game Medium Greedy Farthest Reach
  1. Clarify: Return boolean only?
  2. Pattern: Greedy Farthest Reach
  3. Core: Track the farthest index reachable so far while scanning left to right.
  4. Verify: Input: nums=[2,3,1,1,4] -> true
  5. Trap: Using recursion/DP from each index leads to O(n^2) or worse.
O(n) O(1)
LC 143 Reorder List Medium Find Middle + Reverse + Merge
  1. Clarify: In-place — no new nodes or extra list?
  2. Pattern: Find Middle + Reverse + Merge
  3. Core: Decompose into three subproblems: (1) Find the middle using slow/fast pointers.
  4. Verify: Input: 1→2→3→4
  5. Trap: Missing slow.next = null (severing the list).
O(n) O(1)
LC 238 Product of Array Except Self Medium Prefix-Suffix Product
  1. Clarify: Division forbidden? (Yes)
  2. Pattern: Prefix-Suffix Product
  3. Core: First pass stores left product at each index.
  4. Verify: Input: nums=[1,2,3,4]
  5. Trap: Using total product with division.
O(n) O(1) extra
LC 253 Meeting Rooms II Medium Sort + Min-Heap (End Times)
  1. Clarify: Intervals are half-open or closed? (for this problem, if one ends at time t and another starts at t, they can share room)
  2. Pattern: Sort + Min-Heap (End Times)
  3. Core: Sort meetings by start time.
  4. Verify: Input: intervals=[[0,30],[5,10],[15,20]] -> 2
  5. Trap: Using strict `<` instead of `<=` when checking room reuse treats back-to-back meetings as overlapping and overcounts rooms.
O(n log n) O(n)
LC 419 Battleships in a Board Medium One Pass Grid Scan (Count Ship Heads)
  1. Clarify: Ships are only horizontal or vertical, no L-shapes?
  2. Pattern: One Pass Grid Scan (Count Ship Heads)
  3. Core: Count only the TOP-LEFT cell (head) of each ship.
  4. Verify: Input:
  5. Trap: Running DFS/BFS flood fill works but usually uses extra visited space or mutates the board.
O(m×n) O(1)
LC 647 Palindromic Substrings Medium Expand Around Center
  1. Clarify: Need count of all palindromic substrings, not distinct palindromic values?
  2. Pattern: Expand Around Center
  3. Core: Every palindrome is centered at a character (odd length) or between characters (even length).
  4. Verify: Input: s="abc" -> 3
  5. Trap: Forgetting even centers misses palindromes like "aa" and "abba".
O(n²) O(1)
LC 921 Minimum Add to Make Parentheses Valid Medium Greedy Balance Counter
  1. Clarify: Can we add parentheses anywhere in the string?
  2. Pattern: Greedy Balance Counter
  3. Core: Track open balance.
  4. Verify: Input: s="())" -> 1
  5. Trap: Using a stack is valid but unnecessary.
O(n) O(1)