Tensorum
YouTubeStart learning
1-day revision

Every problem, one page to revise

310 problems, each boiled down to the one idea, its complexity and the trap to avoid. Read it the day before the interview, then open any problem for its full revision card.

Array

Hashing / Anagram

1. Two SumEasyO(n) · O(n)

Store seen values in a map; look up target − num before inserting num.

⚠ Check the map before inserting the current number, so an element is never paired with itself.

217. Contains DuplicateEasyO(n) · O(n)

A set turns 'have I seen this before?' into O(1).

⚠ Sorting mutates the input — fine here, but worth noting.

242. Valid AnagramEasyO(n) · O(1) — 26 counters

One frequency table: +1 for s, −1 for t, all zeros at the end.

⚠ Unicode input would need a dict instead of a fixed 26-slot array.

350. Intersection of Two Arrays IIEasyO(n + m) · O(min(n, m))

Count the smaller array; consume counts while scanning the other.

⚠ Decrement the count so a value isn't used more times than it appears in both.

268. Missing NumberEasyO(n) · O(1)

missing = n(n+1)/2 − sum(nums).

⚠ The range is 0..n inclusive (n+1 values), not 1..n.

136. Single NumberEasyO(n) · O(n) for the set

2·sum(set(nums)) − sum(nums) = the single value (XOR also works).

⚠ XOR of all values gives O(1) extra space: pairs cancel to 0.

49. Group AnagramsMediumO(n · k) with counts (O(n · k log k) with sorting) · O(n · k)

Key = sorted word (or letter-count tuple); group by key.

⚠ Lists aren't hashable — convert the count array to a tuple.

Only expand from run starts (num − 1 not in set).

⚠ Without the 'is it a start?' check the algorithm degrades to O(n²).

Prefix Sum

238. Product of Array Except SelfMediumO(n) · O(1) extra (output excluded)

answer[i] = prefix_product[i] × suffix_product[i].

⚠ Dividing the total product breaks on zeros.

560. Subarray Sum Equals KMediumO(n) · O(n)

count += seen[prefix − k], then record prefix.

⚠ Sliding window doesn't work — values can be negative.

523. Continuous Subarray SumMediumO(n) · O(min(n, k))

Same prefix remainder twice, ≥ 2 apart ⇒ a good subarray.

⚠ Store only the first index of each remainder — overwriting shortens the gap.

Two Pointers

202. Happy NumberEasyO(log n) per step · O(1)

Floyd's cycle detection on the digit-square sequence.

⚠ A set of seen values also works, at O(k) memory.

88. Merge Sorted ArrayEasyO(m + n) · O(1)

Three pointers, filling nums1 from the end.

⚠ Filling from the front would overwrite elements of nums1 you haven't placed yet.

283. Move ZeroesEasyO(n) · O(1)

Two pointers: swap the next non-zero into the first zero slot.

⚠ Order of the non-zero elements must be preserved — swapping keeps it.

27. Remove ElementEasyO(n) · O(1)

Keep-if-not-val with a write index.

⚠ Order beyond the first k elements is irrelevant.

125. Valid PalindromeEasyO(n) · O(1)

Two pointers that skip non-alphanumerics.

⚠ Keep the left < right guard inside the skip loops so they can't cross.

15. 3SumMediumO(n²) · O(n)

Fix one, two-sum the rest with a hash set; dedupe via sorted tuples.

⚠ Without deduplication the same triplet appears many times.

16. 3Sum ClosestMediumO(n²) · O(1)

Sort + two pointers, tracking the smallest |target − sum|.

⚠ Return the sum, not the difference.

18. 4SumMediumO(n³) · O(1) extra

Two fixed loops + two pointers, skipping duplicates at each level.

⚠ Skip duplicates for i, j, left and right — missing any produces repeated answers.

Move the shorter line inward.

⚠ Moving the taller side can never help — that's the proof of correctness.

31. Next PermutationMediumO(n log n) here (O(n) if the tail is reversed instead of sorted) · O(1)

Find the pivot, swap with the next-larger tail value, sort the tail.

⚠ The tail is descending, so reversing it is enough — sorting works but is slower.

189. Rotate ArrayMediumO(n) · O(1)

Reverse all, reverse first k, reverse the rest.

⚠ k can exceed n — take k % n first.

75. Sort ColorsMediumO(n) · O(1)

low / mid / high pointers partition into 0s, 1s, 2s in one pass.

⚠ Don't increment mid after swapping with high.

42. Trapping Rain WaterHardO(n) · O(1) with two pointers

water[i] = min(maxLeft, maxRight) − height[i].

⚠ The pointer on the lower side is safe to resolve; the other side's max can only be higher.

Kadane

53. Maximum SubarrayMediumO(n) · O(1)

A negative prefix never helps a future subarray — reset it to 0.

⚠ Update max_sum before resetting, otherwise an all-negative array returns 0 instead of its largest element.

Matrix

48. Rotate ImageMediumO(n²) · O(1)

Transpose, then mirror each row.

⚠ Start the transpose inner loop at j = i, or every pair is swapped twice (back to the original).

73. Set Matrix ZeroesMediumO(m·n) · O(1) in the final version

Use row 0 / column 0 as markers, plus a col0 flag.

⚠ Process row 0 and column 0 last, or the markers get destroyed.

54. Spiral MatrixMediumO(m·n) · O(1) extra

Four shrinking boundaries; guard the bottom and left passes.

⚠ Without the top ≤ bottom and left ≤ right checks, a single remaining row or column is read twice.

36. Valid SudokuMediumO(81) · O(81)

One set of descriptive keys for rows, columns and boxes.

⚠ Only check filled cells — the board doesn't need to be solvable.

289. Game of LifeMediumO(m·n) · O(1)

In-place state encoding: −1 (dies) and 2 (born).

⚠ board.copy() is shallow — it doesn't protect the rows; the encoding is what makes it correct.

Sorting

56. Merge IntervalsMediumO(n log n) · O(n)

Sort by start; extend or append.

⚠ Touching intervals like [1,4] and [4,5] count as overlapping.

Cyclic Sort / Index Marking

Floyd's cycle detection on index → value pointers.

⚠ The 'do … while' first step matters: both start at nums[0].

41. First Missing PositiveHardO(n) · O(1) in the final version

Use indices as a presence map (sign marks presence).

⚠ Use abs() when reading values — they may already be negated.

Counting Sort

274. H-IndexMediumO(n log n) · O(1)

Sorted descending, h = first i where citations[i] ≤ i.

⚠ A counting-sort version gives O(n).

Moore Voting

169. Majority ElementEasyO(n) · O(1)

Vote: same → +1, different → −1, zero → new candidate.

⚠ This relies on a majority being guaranteed — otherwise verify with a second pass.

229. Majority Element IIMediumO(n) · O(n)

Count and keep values with count > n // 3.

⚠ Extended Boyer–Moore (two candidates) does it in O(1) space.

Linear Scan

Running streak, reset on non-1.

⚠ Update the maximum on every step, not only on resets.

Design

380. Insert Delete GetRandom O(1)MediumO(1) average per operation · O(n)

List + index map; delete by swapping with the last element.

⚠ Update the moved element's index before deleting the removed key (order matters when removing the last element).

String

Two Pointers

344. Reverse StringEasyO(n) · O(1)

Swap s[i] with s[n−1−i] for i < n/2.

⚠ Stop at n // 2 or you'll swap everything back.

680. Valid Palindrome IIEasyO(n) · O(1)

On the first mismatch, try both deletions once.

⚠ Only one deletion is allowed — don't recurse with another deletion budget.

392. Is SubsequenceEasyO(|t|) · O(1)

Greedy two-pointer match.

⚠ An empty s is always a subsequence.

151. Reverse Words in a StringMediumO(n) · O(n) for the character list

Trim → reverse everything → reverse each word.

⚠ Collapse repeated spaces between words to a single one.

Palindrome / Expand Around Center

String Matching (KMP / Rabin-Karp)

686. Repeated String MatchMediumO(n + m) expected · O(n)

Only ceil(|B|/|A|) or one more repeat can work.

⚠ The additive hash collides often — the character check after a hash match is essential.

Hashing / Frequency

205. Isomorphic StringsEasyO(n) · O(1) — bounded alphabet

Compare 'last seen index' of s[i] and t[i].

⚠ Checking only one direction misses cases like 'ab' → 'aa'.

290. Word PatternEasyO(n) · O(n)

Last-seen index per letter and per word must agree.

⚠ Length mismatch is an immediate False.

Parsing / Conversion

13. Roman to IntegerEasyO(n) · O(1)

If cur < next, add next − cur and skip both.

⚠ Guard i + 1 < len(s) when peeking.

6. Zigzag ConversionMediumO(n) · O(n)

Row index bounces 0 → numRows−1 → 0.

⚠ numRows = 1 must return s unchanged (no bouncing).

38. Count and SayMediumO(total length) · O(total length)

Term n = run-length encoding of term n−1.

⚠ Build the result with a list in Python; repeated string concatenation is slower.

Math

50. Pow(x, n)MediumO(log n) · O(1)

Square the base and halve the exponent; peel off one factor when odd.

⚠ Looping n times is too slow for n ≈ 2³¹.

7. Reverse IntegerMediumO(log x) · O(1)

num = num·10 + x % 10, then range-check.

⚠ Overflow check is required: 1534236469 reversed overflows.

Prefix / Misc

14. Longest Common PrefixEasyO(S) — total characters · O(1)

Shrink a candidate prefix until every word starts with it.

⚠ Return early when the prefix becomes empty.

Sliding Window

76. Minimum Window SubstringHardO(|s| + |t|) · O(Σ)

Expand to valid, shrink to minimal; 'formed' counts satisfied characters.

⚠ formed should change only when a count crosses the requirement exactly.

Sliding Window

Fixed Window

Last-seen index map; compare distance.

⚠ Always update to the latest index — older ones are farther away.

438. Find All Anagrams in a StringMediumO(n · 26) · O(26)

Fixed window of len(p); compare frequency counts.

⚠ Remove zero entries from a Counter, or the equality check fails.

567. Permutation in StringMediumO(n) · O(Σ)

Fixed-size window with matching counts.

⚠ Delete zero counts so dict comparison is accurate.

Variable Window – Longest

Longest window with ≤ k zeros.

⚠ The window never shrinks, only slides — that's fine because we only need the max length.

Variable Window – Shortest / Minimum

Positive numbers ⇒ expand then shrink.

⚠ Sliding window relies on positivity — with negatives use prefix sums.

Counting Subarrays (Exactly K = AtMost K − AtMost K−1)

Window + Hashing (Multi-word)

Monotonic Queue

Monotonic decreasing deque; front = window max.

⚠ Store indices, not values — you need them to expire elements.

Prefix / Circular Window

Linked List

Basics

Fast & Slow Pointers

141. Linked List CycleEasyO(n) · O(1)

Floyd: fast meets slow ⇔ cycle.

⚠ Compare nodes (identity), not values.

142. Linked List Cycle IIMediumO(n) · O(1)

Meet, reset one to head, step together → cycle start.

⚠ Return null when phase 1 ends without meeting.

Reversal

206. Reverse Linked ListEasyO(n) · O(1)

prev ← temp ← front, one arrow at a time.

⚠ Save temp.next before overwriting it.

92. Reverse Linked List IIMediumO(n) · O(1)

Detach [left, right], reverse, reconnect both ends.

⚠ left = 1 has no previous node — the head changes.

61. Rotate ListMediumO(n) · O(1)

Ring, then cut after length − k % length nodes.

⚠ Empty list returns immediately.

Find kth node → detach → reverse → reconnect.

⚠ Track prev_node across groups so they stay connected.

Merge

23. Merge k Sorted ListsHardO(N log k) · O(k) for the round list

Pairwise merging rounds — O(N log k).

⚠ Merging one by one into a growing list is O(N·k).

Palindrome

Middle → reverse second half → compare.

⚠ Restoring the list is good practice — callers may reuse it.

Reordering / Partition

86. Partition ListMediumO(n) · O(1)

Two dummy chains, then concatenate.

⚠ Set temp2.next = None or the list may loop.

Intersection

Deep Copy / Multilevel

Design

146. LRU CacheMediumO(1) per operation · O(capacity)

Hash map + doubly linked list with sentinels.

⚠ Sentinel head and tail remove all null checks.

460. LFU CacheHardO(1) per operation · O(capacity)

freq → OrderedDict buckets + min_freq.

⚠ Ties at the same frequency are broken by recency — hence the ordered buckets.

Sorting

148. Sort ListMediumO(n log n) · O(log n) recursion

Split at the middle, sort halves, merge.

⚠ Cut the list at the middle (midPrev.next = None) or the recursion never ends.

Arithmetic

2. Add Two NumbersMediumO(max(m, n)) · O(max(m, n)) output

Grade-school addition with a carry.

⚠ Keep looping for a final carry (999 + 1).

Stack & Queue

Parentheses / Bracket Matching

20. Valid ParenthesesEasyO(n) · O(n)

Push openers; each closer must match the top.

⚠ Leftover openers like '((' make it invalid.

1249. Minimum Remove to Make Valid ParenthesesMediumO(n) with a set (O(n²) with indexOf) · O(n)

Stack of '(' indices; collect unmatched indices; rebuild.

⚠ Checking membership with indexOf on an array is O(n) per character — a set is better.

Two counters: optimistic opens forward, optimistic closes backward.

⚠ A '*' before a '(' can't close it — the stack version checks index order.

Stack Simulation / String Processing

71. Simplify PathMediumO(n) · O(n)

Stack of directory names.

⚠ '...' is a valid directory name, not a parent reference.

Expression Evaluation

224. Basic CalculatorHardO(n) · O(n)

Stack saves (answer, sign) at each '('.

⚠ Step back one index after reading a multi-digit number.

Stack / Queue Design

225. Implement Stack using QueuesEasyO(n) push, O(1) pop/top · O(n)

Rotate after each push so the newest is at the front.

⚠ One queue is enough; the two-queue version is commented out in the code.

232. Implement Queue using StacksEasyO(n) push, O(1) pop/peek · O(n)

Make push expensive so the oldest item stays on top.

⚠ The amortised two-stack version makes pop O(1) amortised instead.

155. Min StackMediumO(1) per operation · O(n)

Push (value, min so far) pairs.

⚠ A single 'current min' variable can't recover the old min after a pop.

Iterator (Stack-based)

173. Binary Search Tree IteratorMediumO(1) amortised next · O(h)

Controlled in-order traversal with a stack of left spines.

⚠ Flattening the whole tree up front uses O(n) memory instead of O(h).

Queue Simulation

Monotonic Stack – Next / Previous Greater or Smaller

496. Next Greater Element IEasyO(n + m) · O(n)

Monotonic decreasing stack over nums2 + hash map.

⚠ Values are unique, so mapping by value is safe.

Loop 2n−1 → 0 with i % n; monotonic stack.

⚠ Pop on equal values too — 'greater' is strict.

Monotonic Stack – Greedy Removal

402. Remove K DigitsMediumO(n) · O(n)

Monotonic increasing stack; pop larger previous digits while k > 0.

⚠ Leftover k comes off the end (the stack is increasing there).

Monotonic Stack – Contribution / Area

Monotonic stack; width = i − stack_top − 1 when popping.

⚠ The −1 sentinel gives the correct width at the left edge.

85. Maximal RectangleHardO(m · n) · O(n)

Row-by-row histograms + largest-rectangle-in-histogram.

⚠ The −1 sentinel on the stack makes the width formula work at the left edge.

Tree

Traversals (Recursive / Iterative)

Left → right → node.

⚠ Iterative post-order is the trickiest of the three — reversed (node, right, left) is a neat shortcut.

DFS Basics

226. Invert Binary TreeEasyO(n) · O(h)

Swap children at every node.

⚠ Order doesn't matter — pre-order swapping works too.

100. Same TreeEasyO(n) · O(h)

Compare roots and recurse in lockstep.

⚠ Check the None cases before reading .val.

101. Symmetric TreeEasyO(n) · O(h)

Mirror check: outer with outer, inner with inner.

⚠ Compare cross-wise, not left-with-left.

572. Subtree of Another TreeEasyO(m · n) · O(h)

isSubtree = sameTree(root, sub) or recurse into children.

⚠ Matching values aren't enough — the whole structure below must match (example 2).

Height DFS that returns −1 on imbalance.

⚠ Computing height separately at every node is O(n²).

Root-to-Leaf Paths

112. Path SumEasyO(n) · O(h)

Reduce the target; check at leaves.

⚠ Only leaf-to-root paths count — an internal node hitting zero isn't enough.

129. Sum Root to Leaf NumbersMediumO(n · h) with strings (O(n) with path·10 + val) · O(h)

Carry the path's digits; add at leaves.

⚠ path·10 + val avoids string building.

BFS / Level Order

Right-first DFS; record the first node per level.

⚠ A left-only branch deeper than the right side is still visible.

Heap indices per level, normalised by the level's first index.

⚠ Without normalising, indices overflow in languages with fixed-width ints.

Lowest Common Ancestor / Distance

BST

Pass (min, max) bounds down the tree.

⚠ Comparing only with the direct parent misses violations deeper down (example 2).

450. Delete Node in a BSTMediumO(h) · O(h)

Replace with successor/predecessor, then delete that one.

⚠ Reassign root.left / root.right with the recursive result.

Construction / Serialization

Tree DP

diameter = max over nodes of (left height + right height).

⚠ The path doesn't have to pass through the root.

337. House Robber IIIMediumO(n) · O(n)

State (node, can_rob); robbing forbids the children.

⚠ Returning a (rob, skip) pair per node avoids the memo dictionary entirely.

124. Binary Tree Maximum Path SumHardO(n) · O(h) recursion

Update the answer with both sides; return only one side to the parent.

⚠ Start the global best at −∞ — an all-negative tree must return its largest value.

Heap

Top K

215. Kth Largest Element in an ArrayMediumO(n log k) heap · O(n + range) counting · O(k) · O(range)

Min-heap of size k; top = kth largest.

⚠ Shift by −min so negative values index correctly.

658. Find K Closest ElementsMediumO(log n + k) · O(1) extra

bisect to x, then expand the closer side.

⚠ Ties go to the smaller element (the left side).

Two Heaps

295. Find Median from Data StreamHardO(log n) add, O(1) median · O(n)

Two heaps: max-heap low half, min-heap high half.

⚠ Python only has min-heaps — store negatives for the max-heap.

502. IPOHardO(n log n + k log n) · O(n)

Sort by capital; max-heap of affordable profits.

⚠ Unaffordable projects aren't discarded — they may become affordable later.

K-way Merge

Greedy + Heap / Scheduling

621. Task SchedulerMediumO(T · log 26) · O(26)

Max-heap of counts + cooldown queue.

⚠ The formula (maxCount − 1)·(n + 1) + #maxCount gives the answer in O(T) without simulating.

Recursion & Backtracking

Recursion Basics

1922. Count Good NumbersMediumO(log n) · O(1)

5^ceil(n/2) · 4^floor(n/2) mod 1e9+7.

⚠ n can be 10¹⁵ — exponentiation by squaring is required.

Subsets

78. SubsetsMediumO(n · 2ⁿ) · O(n) recursion

Record at every node; extend with later indices.

⚠ Record a copy (subs[:]) — the list keeps changing.

90. Subsets IIMediumO(n · 2ⁿ) · O(n)

Sort; skip nums[i] == nums[i−1] when i > index.

⚠ The condition is i != index (same level), not i > 0.

Combinations

77. CombinationsMediumO(k · C(n, k)) · O(k)

Backtrack with a start index; stop at size k.

⚠ Pruning when not enough numbers remain (n − i + 1 < k − len) speeds it up.

39. Combination SumMediumO(2^(T/min)) · O(T/min)

Recurse with the same index to allow reuse.

⚠ Starting the loop at start (not 0) prevents permutations of the same combination.

40. Combination Sum IIMediumO(2ⁿ) · O(n)

Sort; skip same-level duplicates; break on overshoot.

⚠ Break, don't continue — every later candidate is even bigger.

216. Combination Sum IIIMediumO(C(9, k)) · O(k)

Backtrack over 1..9 with count and sum checks.

⚠ The duplicate check is harmless here — digits are already unique.

Permutations

46. PermutationsMediumO(n · n!) · O(n)

Fix position start, swap each choice into it.

⚠ `num not in ds` costs O(n) and breaks with duplicate values.

47. Permutations IIMediumO(n · n!) · O(n)

Backtrack over a frequency map, not over indices.

⚠ Iterating the Counter keys means each value is tried once per level.

Generate / Build Strings

22. Generate ParenthesesMediumO(4ⁿ / √n) · O(n)

Add '(' if left < n; add ')' if right < left.

⚠ Never let closes exceed opens.

Partitioning

131. Palindrome PartitioningMediumO(n · 2ⁿ) · O(n²) for the table

Backtracking over palindromic prefixes; a dp table can remember which substrings are palindromes.

⚠ Append a copy (parts[:]) — the list keeps changing.

Constraint Satisfaction

51. N-QueensHardO(n!) · O(n²) board

Column-by-column backtracking with row + diagonal hashes.

⚠ Only check to the left — columns to the right are still empty.

52. N-Queens IIHardO(n!) · O(n)

Backtracking that returns the number of solutions.

⚠ The board array isn't needed for counting — the hashes are enough.

37. Sudoku SolverHardO(9^m) for m empty cells · O(m) recursion

Backtracking over empty cells with a validity check.

⚠ The box index is 3·(row//3) + i//3, 3·(col//3) + i%3.

Track prev_operand to fix up multiplication precedence.

⚠ Numbers like '05' are invalid — skip multi-digit numbers starting with 0.

Grid Search / Backtracking DFS

79. Word SearchMediumO(m · n · 3^L) · O(L)

Grid DFS with a path-visited set.

⚠ Un-mark on the way back so other paths can reuse the cell.

Greedy

Sorting + Simple Greedy

455. Assign CookiesEasyO(n log n + m log m) · O(1)

Sort both; smallest sufficient cookie per child.

⚠ Skip cookies that are too small rather than skipping children.

12. Integer to RomanMediumO(1) · O(1)

Greedy over values including subtractive pairs.

⚠ Without CM, XC, IV, etc. you'd produce 'VIIII'.

Jump / Reachability

55. Jump GameMediumO(n) · O(1)

Move the goal left whenever i + nums[i] ≥ goal.

⚠ A zero only matters if nothing before it can jump past it.

45. Jump Game IIMediumO(n) · O(1)

Implicit BFS over index windows.

⚠ Already at the end (n = 1) means 0 jumps.

134. Gas StationMediumO(n) · O(1)

Reset the start after any negative running tank.

⚠ The total check is what guarantees the found start completes the loop.

Sum of all positive deltas = best profit with unlimited trades.

⚠ This greedy only works because transactions are unlimited and free — fees or cooldowns need the DP versions.

Local Choice / Two-pass

135. CandyHardO(n) · O(n) two-pass · O(1) slope

Two passes, take the max.

⚠ Equal ratings don't need more candy.

Intervals

57. Insert IntervalMediumO(n) · O(n)

Three phases: before, overlap-merge, after.

⚠ Touching intervals ([1,2] and [2,3]) overlap.

435. Non-overlapping IntervalsMediumO(n log n) · O(1)

Sort by end; count overlaps with the last kept.

⚠ Sorting by start instead needs extra logic to keep the smaller end.

Graph

Graph Fundamentals / BFS

133. Clone GraphMediumO(V + E) · O(V)

original → copy map as both cache and visited set.

⚠ Store the copy before recursing, or cycles loop forever.

200. Number of IslandsMediumO(m · n) · O(m · n)

Count DFS launches from unvisited land.

⚠ Deep recursion on huge grids — BFS or marking the grid in place avoids it.

Graph Fundamentals / DFS

733. Flood FillEasyO(m · n) · O(m · n)

DFS through cells of the starting colour.

⚠ If the new colour equals the old one, a visited set (or early return) prevents infinite loops.

841. Keys and RoomsMediumO(N + K) · O(N)

BFS from room 0 over key edges.

⚠ A key to an already-visited room is ignored.

1020. Number of EnclavesMediumO(m · n) · O(m · n)

Flood from the border, count the rest.

⚠ Think in reverse — find what escapes, not what's trapped.

130. Surrounded RegionsMediumO(m · n) · O(m · n)

Mark border-connected O's, flip the rest.

⚠ Searching from interior O's is much harder — start from the border.

Graph Fundamentals / DFS + DSU

547. Number of ProvincesMediumO(n²) · O(n)

Count connected components with DFS.

⚠ The matrix is symmetric — no need to look at both triangles specially.

Multi-Source BFS

542. 01 MatrixMediumO(m · n) · O(m · n)

Multi-source BFS from every 0.

⚠ A BFS per 1-cell would be O((mn)²).

994. Rotting OrangesMediumO(m · n) · O(m · n)

Multi-source BFS from rotten oranges; check none stay fresh.

⚠ No fresh oranges at all → 0 minutes.

State-Space BFS

433. Minimum Genetic MutationMediumO(B · L · 4) · O(B)

BFS over one-letter mutations in the bank.

⚠ Use a set for the bank — list membership is O(B).

909. Snakes and LaddersMediumO(n²) · O(n²)

BFS over squares; zig-zag coordinate conversion.

⚠ Only follow one snake/ladder per move (no chaining).

Bipartite / 2-Coloring

785. Is Graph Bipartite?MediumO(V + E) · O(V)

BFS 2-colouring per component.

⚠ The graph can be disconnected — start a BFS from every uncoloured node.

Topological Sort / DAG

207. Course ScheduleMediumO(V + E) · O(V + E)

Cycle detection with path-visited markers.

⚠ visited alone isn't enough — a node finished in another branch isn't a cycle.

210. Course Schedule IIMediumO(V + E) · O(V + E)

DFS post-order, reversed = topological order.

⚠ Many orders are valid — any topological order is accepted.

802. Find Eventual Safe StatesMediumO(V + E) · O(V)

Three-colour DFS; safe = finished without touching the path.

⚠ Leave unsafe nodes at state 1 — that's what marks them.

State-Space / Transformation BFS

399. Evaluate DivisionMediumO(Q · (V + E)) · O(V + E)

Weighted graph; multiply along a BFS path.

⚠ x / x is 1 only if x appears in some equation.

127. Word LadderHardO(N · L · 26) · O(N)

BFS generating one-letter neighbours; remove words once used.

⚠ Removing words from the set doubles as the visited set.

126. Word Ladder IIHardexponential in the number of paths · O(N · L)

BFS for levels, then DFS backwards along level − 1.

⚠ Searching backwards avoids exploring dead branches.

Shortest Path / Dijkstra

743. Network Delay TimeMediumO(E log V) · O(V + E)

Dijkstra from k; answer = max distance.

⚠ Nodes are 1-indexed; ignore dist[0].

1631. Path With Minimum EffortMediumO(m·n log(m·n)) · O(m · n)

Dijkstra with max() instead of +.

⚠ Binary search on the effort + BFS is an alternative.

Shortest Path / Floyd-Warshall

Minimum Spanning Tree

778. Swim in Rising WaterHardO(n² log n) · O(n²)

Min-heap of max-height-so-far along the path.

⚠ Binary search on time + BFS also works.

Union Find / DSU

721. Accounts MergeMediumO(M log M) · O(M + N)

Union accounts sharing an email.

⚠ Names can repeat across different people — only shared emails merge accounts.

827. Making A Large IslandHardO(n²) · O(n²)

DSU sizes + try flipping each 0.

⚠ Use a set of neighbour roots so the same island isn't counted twice.

684. Redundant ConnectionMediumO(n α(n)) · O(n)

First edge connecting an already-connected pair.

⚠ Returning the first such edge matches 'the last one in input order' since only one edge closes the cycle.

Bridges / Articulation Points

Graph DP

Shortest Path / BFS-Dijkstra

787. Cheapest Flights Within K StopsMediumO(E · k · log(E · k)) · O(E · k)

Heap on (cost, node, stops); skip when stops > k or stops ≥ fewest stops already seen at that node.

⚠ Standard 'visited' marking breaks this problem — a pricier path with fewer stops may be the only valid one.

Graph Fundamentals / DFS-BFS

417. Pacific Atlantic Water FlowMediumO(m · n) · O(m · n)

Reverse BFS from each ocean; intersect.

⚠ Water flows downhill, so the reverse search climbs uphill.

Dynamic Programming

1D / Fibonacci

70. Climbing StairsEasyO(n) · O(1) in the final version (O(n) for memo / table)

ways(n) = ways(n-1) + ways(n-2), with ways(0) = ways(1) = 1.

⚠ Plain recursion without the memo is exponential.

509. Fibonacci NumberEasyO(n) · O(1)

F(i) only depends on F(i-1) and F(i-2), so two rolling variables are enough.

⚠ The naive recursion is O(2^n) — fine for n ≤ 30 here, but it is the classic reason to memoise.

dp[i] = cost[i] + min(dp[i-1], dp[i-2]); answer = min(dp[n-1], dp[n-2]).

⚠ The answer is not dp[n-1] alone — you can step to the top from n-2 as well.

198. House RobberMediumO(n) · O(n) (reducible to O(1) with two variables)

best(i) = max(nums[i] + best(i-2), best(i-1)).

⚠ A single house must return nums[0] before dp[1] is read.

213. House Robber IIMediumO(n) · O(n)

Circle → max(rob_line(nums[1:]), rob_line(nums[:-1])).

⚠ With one house, slicing both ends would leave nothing — handle len == 1 first.

Kadane / Subarray DP

The best product is always a prefix or a suffix of some zero-free segment.

⚠ Initialise the answer to −∞, not 0 — an all-negative single element like [-2] must return -2.

918. Maximum Sum Circular SubarrayMediumO(n) · O(n) for the negated copy (O(1) possible)

answer = max(kadane(nums), total − min_subarray(nums)), unless everything is negative.

⚠ All-negative input: total − min would be 0 (empty subarray), which isn't allowed.

State Machine / Stocks

Effective second buy = price − best first profit.

⚠ Splitting the array at every point and running two separate scans works but is easier to get wrong.

min_buy[i] = min(min_buy[i], price − max_profit[i-1]); max_profit[i] = max(max_profit[i], price − min_buy[i]).

⚠ Note the argument order: k comes before prices.

Grid DP

3418. Maximum Amount of Money Robot Can EarnMediumO(m · n · 3) · O(m · n · 3)

State = (i, j, k neutralisations left); at each cell try 'neutralise' and 'don't'.

⚠ Neutralising a positive cell wastes budget — max(coin, 0) keeps it harmless but the k-1 branch is still explored.

931. Minimum Falling Path SumMediumO(n²) · O(n²) (one previous row would do)

dp[i][j] = matrix[i][j] + min(dp[i-1][j-1], dp[i-1][j], dp[i-1][j+1]).

⚠ The right-edge check uses m-1; it works because the matrix is square (m = n).

64. Minimum Path SumMediumO(m · n) · O(m · n)

dp[i][j] = grid[i][j] + min(dp[i][j-1], dp[i-1][j]).

⚠ Skip (0, 0) inside the loop or you'll add it twice.

62. Unique PathsMediumO(min(m, n)) for the formula · O(m·n) for the DP · O(1) for the formula

paths(i, j) = paths(i-1, j) + paths(i, j-1) — or simply C(m+n-2, n-1).

⚠ In the memo version the i == 0 or j == 0 check must come before the negative check (it does).

63. Unique Paths IIMediumO(m · n) · O(m · n)

Obstacle cell ⇒ dp = 0; otherwise dp = left + up.

⚠ A blocked start or finish must return 0.

Triangle / Pascal

118. Pascal's TriangleEasyO(numRows²) · O(numRows²) for the output

row[c] = prev[c-1] + prev[c], edges are 1.

⚠ prev is only read for inner cells, so row 0 never touches it.

119. Pascal's Triangle IIEasyO(r) · O(r) for the output

C(r, i+1) = C(r, i) · (r − i) / (i + 1).

⚠ Multiply before dividing so the integer division stays exact.

120. TriangleMediumO(n²) · O(n²) (one row would do)

dp[row][col] = triangle[row][col] + min(dp[row+1][col], dp[row+1][col+1]).

⚠ Going bottom-up removes the need to take a min over the last row at the end.

0/1 Knapsack / Subset Sum

416. Partition Equal Subset SumMediumO(n · target) · O(n · target)

Equal partition ⇔ a subset sums to total / 2 (and total must be even).

⚠ Only seed dp[0][nums[0]] when nums[0] ≤ target.

494. Target SumMediumO(n · tar) · O(tar) in the final version

Count subsets with sum (total + target) / 2 — a 0/1 knapsack count.

⚠ Handle nums[0] == 0 in the base case — both [] and [0] reach sum 0.

Unbounded Knapsack

322. Coin ChangeMediumO(n · amount) · O(n · amount)

Unbounded knapsack: include ⇒ 1 + dp[same coin][amount − coin].

⚠ Greedy 'largest coin first' fails (e.g. coins [1,3,4], amount 6).

518. Coin Change IIMediumO(n · amount) · O(n · amount)

ways[i][a] = ways[i-1][a] + ways[i][a − coin].

⚠ Looping amounts outer and coins inner counts permutations, not combinations.

279. Perfect SquaresMediumO(n · √n) · O(n)

dp[x] = 1 + min(dp[x − s]) over squares s ≤ x.

⚠ Break out of the squares loop once a square exceeds x.

String DP / Word Break

91. Decode WaysMediumO(n) · O(n)

ways(i) = ways(i+1) [if s[i] ≠ '0'] + ways(i+2) [if s[i:i+2] ≤ 26].

⚠ '06' is invalid — the zero check comes before taking two digits.

97. Interleaving StringMediumO(m · n) · O(m · n)

State (i, j) — k is always i + j, so only two indices matter.

⚠ Greedy 'take from s1 when it matches' fails when both strings share a character.

139. Word BreakMediumO(n² · L) with substring slicing · O(n)

dp[end] = any(dp[start] and s[start:end] ∈ words).

⚠ Without memo, the recursive version explodes on inputs like 'aaaa…b'.

472. Concatenated WordsHardO(N · L²) roughly · O(N · L) for the cache

Word Break per word, with the prefix limited to a strict prefix so the word can't match itself.

⚠ Using range(1, len(word)+1) would let a word match itself and return every word.

72. Edit DistanceMediumO(m · n) · O(m · n)

dist(i, j) = dist(i-1, j-1) if chars match else 1 + min(insert, delete, replace).

⚠ Using lengths (1-based) as indices keeps the empty-string base cases simple — remember to read word[i-1].

698. Partition to K Equal Sum SubsetsMediumO(k · 2ⁿ) worst case · O(2ⁿ) memo

Once k-1 buckets are full, the remaining numbers must fill the last one.

⚠ Undo the 'taken' mark after each try (backtracking).

44. Wildcard MatchingHardO(m · n) · O(m · n)

'*' ⇒ dp(i, j+1) or dp(i+1, j).

⚠ The 'string empty' base case must allow a run of trailing stars.

140. Word Break IIHardO(2ⁿ) worst case (output can be exponential) · O(n) recursion

Backtracking over prefix words; a full path is one sentence.

⚠ Pop after recursing or later sentences inherit stale words.

LCS

1143. Longest Common SubsequenceMediumO(m · n) · O(n) in the final version

lcs(i, j) = 1 + lcs(i+1, j+1) on a match, else max(lcs(i+1, j), lcs(i, j+1)).

⚠ Subsequence ≠ substring — characters don't have to be contiguous.

Interval DP: dp[i][j] = 2 + dp[i+1][j-1] if s[i] == s[j] else max(dp[i+1][j], dp[i][j-1]).

⚠ Loop order matters — start must go downward so dp[start+1][…] is already filled.

718. Maximum Length of Repeated SubarrayMediumO(m · n) · O(m · n)

Like LCS, but a mismatch resets to 0 and the answer is the max cell, not the corner.

⚠ Don't take max of neighbours on a mismatch — that would compute a subsequence instead.

115. Distinct SubsequencesHardO(m · n) · O(m · n)

match ⇒ ways(i+1, j+1) + ways(i+1, j); else ways(i+1, j).

⚠ Check 't finished' before 's finished' — an empty t matches in exactly one way.

1092. Shortest Common SupersequenceHardO(m · n) · O(m · n)

LCS table, then reconstruct while emitting skipped characters.

⚠ Characters you'd skip for the LCS must still appear in the supersequence.

LIS

368. Largest Divisible SubsetMediumO(n²) · O(n)

Sorted + 'divides' is transitive ⇒ it's LIS with % instead of <.

⚠ Sorting first is what makes checking only the last element enough.

873. Length of Longest Fibonacci SubsequenceMediumO(n² · log M) (each chain grows like Fibonacci) · O(n)

Two numbers fix the whole sequence — extend each pair with a set lookup.

⚠ Length 2 alone doesn't count — the answer must be at least 3 or 0.

300. Longest Increasing SubsequenceMediumO(n log n) · O(n)

Patience sorting: tails stay sorted, so bisect_left finds where each number belongs.

⚠ Use bisect_left for strictly increasing; bisect_right allows equal values.

354. Russian Doll EnvelopesHardO(n log n) · O(n)

Sort (w ↑, h ↓), then LIS on heights.

⚠ Without height-descending on ties, [3,4] and [3,5] would wrongly nest.

Palindrome / Interval DP

dp[end] = min over palindromic s[start..end] of (0 if start == 0 else dp[start-1] + 1).

⚠ Backtracking over all partitions (like Palindrome Partitioning) is exponential — this needs the DP.

DP on Squares / Matrix

221. Maximal SquareMediumO(m · n) · O(m · n)

dp = 1 + min(up, left, diagonal); answer = max side².

⚠ The matrix holds characters '0'/'1', not integers.

Game DP

1025. Divisor GameEasyO(1) final (O(n²) for the table) · O(1)

Win ⇔ n is even.

⚠ n = 1 is a loss: no x with 0 < x < 1 exists.

877. Stone GameMediumO(1) final (O(n²) for minimax) · O(1)

Minimax on (i, j, turn) — and with an even pile count Alice can always win.

⚠ The 'return True' trick depends on an even pile count and an odd total — read the constraints before using it.

DP on Array

403. Frog JumpHardO(n²) · O(n²)

State = (stone index, last jump); a hash map turns 'is there a stone at x?' into O(1).

⚠ The first jump must be exactly 1 — starting with prev_jump = 0 enforces it.

Top Interview 150

Other

222. Count Complete Tree NodesMediumO(n) · O(log n) for a complete tree

count = 1 + count(left) + count(right).

⚠ Comparing left and right heights gives O(log² n) by using completeness.

58. Length of Last WordEasyO(n) · O(1)

Skip trailing spaces, count back to a space.

⚠ Trailing spaces are the trap.

9. Palindrome NumberEasyO(log x) · O(1)

Reverse half the digits and compare.

⚠ Converting to a string works but isn't the intended trick.

66. Plus OneEasyO(n) · O(1) (O(n) when growing)

Carry propagation from the right.

⚠ [9,9,9] becomes [1,0,0,0].

383. Ransom NoteEasyO(m + n) · O(1) — 26 letters

Counter(magazine) ≥ Counter(note) letter by letter.

⚠ Each magazine letter can be used once.

427. Construct Quad TreeMediumO(n² log n) · O(log n)

Uniform square → leaf; else recurse on 4 quadrants.

⚠ Checking uniformity by scanning at every level costs O(n² log n); prefix sums can make it O(n²).

149. Max Points on a LineHardO(n²) · O(n)

Per anchor, group other points by slope.

⚠ Floating-point slopes can collide or differ by rounding; a reduced (dy, dx) pair with gcd is exact.

68. Text JustificationHardO(total characters) · O(maxWidth)

Greedy packing + even/remainder space distribution.

⚠ Left gaps get the remainder, not the right ones.

Tree

Hard 50

Advanced / Mixed

432. All O`one Data StructureHardO(1) inc/dec, O(#buckets) for max/min here · O(n)

count map + count → keys buckets.

⚠ max()/min() over bucket keys isn't O(1) — a doubly linked list of buckets makes every operation O(1).

493. Reverse PairsHardO(n log n) · O(n)

Merge sort; count cross pairs before each merge.

⚠ Count before merging — the halves must still be separate.

Tree

Post-order returning (sum, min, max) or 'not a BST'.

⚠ The best sum starts at 0 — an all-negative tree returns 0 (empty BST).