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.
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.
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.
A set turns 'have I seen this before?' into O(1).
⚠ Sorting mutates the input — fine here, but worth noting.
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.
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.
missing = n(n+1)/2 − sum(nums).
⚠ The range is 0..n inclusive (n+1 values), not 1..n.
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.
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²).
answer[i] = prefix_product[i] × suffix_product[i].
⚠ Dividing the total product breaks on zeros.
count += seen[prefix − k], then record prefix.
⚠ Sliding window doesn't work — values can be negative.
Same prefix remainder twice, ≥ 2 apart ⇒ a good subarray.
⚠ Store only the first index of each remainder — overwriting shortens the gap.
Floyd's cycle detection on the digit-square sequence.
⚠ A set of seen values also works, at O(k) memory.
Three pointers, filling nums1 from the end.
⚠ Filling from the front would overwrite elements of nums1 you haven't placed yet.
Two pointers: swap the next non-zero into the first zero slot.
⚠ Order of the non-zero elements must be preserved — swapping keeps it.
Write pointer advances only on a new value.
⚠ Compare with nums[i−1] (the original neighbour), not with the write slot.
Keep-if-not-val with a write index.
⚠ Order beyond the first k elements is irrelevant.
Two pointers that skip non-alphanumerics.
⚠ Keep the left < right guard inside the skip loops so they can't cross.
Sorted ⇒ two pointers squeeze toward the target.
⚠ The answer is 1-indexed.
Fix one, two-sum the rest with a hash set; dedupe via sorted tuples.
⚠ Without deduplication the same triplet appears many times.
Sort + two pointers, tracking the smallest |target − sum|.
⚠ Return the sum, not the difference.
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.
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.
Keep nums[i] unless it equals nums[insert_index − 2].
⚠ Compare against the write area, not the read area — that's what limits copies to two.
Reverse all, reverse first k, reverse the rest.
⚠ k can exceed n — take k % n first.
low / mid / high pointers partition into 0s, 1s, 2s in one pass.
⚠ Don't increment mid after swapping with high.
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.
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.
Transpose, then mirror each row.
⚠ Start the transpose inner loop at j = i, or every pair is swapped twice (back to the original).
Use row 0 / column 0 as markers, plus a col0 flag.
⚠ Process row 0 and column 0 last, or the markers get destroyed.
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.
One set of descriptive keys for rows, columns and boxes.
⚠ Only check filled cells — the board doesn't need to be solvable.
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.
Sort by start; extend or append.
⚠ Touching intervals like [1,4] and [4,5] count as overlapping.
Floyd's cycle detection on index → value pointers.
⚠ The 'do … while' first step matters: both start at nums[0].
Use indices as a presence map (sign marks presence).
⚠ Use abs() when reading values — they may already be negated.
Sorted descending, h = first i where citations[i] ≤ i.
⚠ A counting-sort version gives O(n).
Vote: same → +1, different → −1, zero → new candidate.
⚠ This relies on a majority being guaranteed — otherwise verify with a second pass.
Count and keep values with count > n // 3.
⚠ Extended Boyer–Moore (two candidates) does it in O(1) space.
Running streak, reset on non-1.
⚠ Update the maximum on every step, not only on resets.
Count descents including the wrap-around; ≤ 1 means yes.
⚠ Equal neighbours are not drops.
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).
Swap s[i] with s[n−1−i] for i < n/2.
⚠ Stop at n // 2 or you'll swap everything back.
On the first mismatch, try both deletions once.
⚠ Only one deletion is allowed — don't recurse with another deletion budget.
Greedy two-pointer match.
⚠ An empty s is always a subsequence.
Trim → reverse everything → reverse each word.
⚠ Collapse repeated spaces between words to a single one.
Expand around centre: odd (i, i) and even (i, i+1).
⚠ Forgetting the even centre misses answers like 'bb'.
Check every start position until one fully matches.
⚠ KMP brings this down to O(n + m).
Only ceil(|B|/|A|) or one more repeat can work.
⚠ The additive hash collides often — the character check after a hash match is essential.
Compare 'last seen index' of s[i] and t[i].
⚠ Checking only one direction misses cases like 'ab' → 'aa'.
Last-seen index per letter and per word must agree.
⚠ Length mismatch is an immediate False.
If cur < next, add next − cur and skip both.
⚠ Guard i + 1 < len(s) when peeking.
Strip → sign → digits → clamp.
⚠ Stop at the first non-digit — 'words 987' is 0.
Row index bounces 0 → numRows−1 → 0.
⚠ numRows = 1 must return s unchanged (no bouncing).
Parse revisions in lockstep; missing = 0.
⚠ '1.0' and '1.0.0.0' are equal.
Term n = run-length encoding of term n−1.
⚠ Build the result with a list in Python; repeated string concatenation is slower.
Square the base and halve the exponent; peel off one factor when odd.
⚠ Looping n times is too slow for n ≈ 2³¹.
num = num·10 + x % 10, then range-check.
⚠ Overflow check is required: 1534236469 reversed overflows.
Shrink a candidate prefix until every word starts with it.
⚠ Return early when the prefix becomes empty.
Expand to valid, shrink to minimal; 'formed' counts satisfied characters.
⚠ formed should change only when a count crosses the requirement exactly.
Last-seen index map; compare distance.
⚠ Always update to the latest index — older ones are farther away.
Fixed window of len(p); compare frequency counts.
⚠ Remove zero entries from a Counter, or the equality check fails.
Fixed-size window with matching counts.
⚠ Delete zero counts so dict comparison is accurate.
On a repeat, l = max(l, last[ch] + 1).
⚠ Use max() — an old occurrence before l must not drag l backwards ('abba').
valid ⇔ window − maxFreq ≤ k.
⚠ max(mpp.values()) each step is O(26) — fine; tracking a running max avoids it.
Longest window with ≤ k zeros.
⚠ The window never shrinks, only slides — that's fine because we only need the max length.
Positive numbers ⇒ expand then shrink.
⚠ Sliding window relies on positivity — with negatives use prefix sums.
exactly(k) = atMost(k) − atMost(k − 1).
⚠ atMost(−1) must return 0.
Odd → 1, then exactly(k) = atMost(k) − atMost(k − 1).
⚠ Same atMost trick — only the value mapping changes.
Ending at i, valid starts = 1 + min(last a, last b, last c).
⚠ Count by end position to avoid double-counting.
exactly(k) = atMost(k) − atMost(k − 1) with a count map.
Word-sized sliding window, run once per offset.
⚠ Different offsets are independent windows — you need all of them.
Monotonic decreasing deque; front = window max.
⚠ Store indices, not values — you need them to expire elements.
Slide k picks from all-left to all-right.
⚠ Equivalent: minimise the middle window of length n − k.
Halve [low, high] around mid until found or empty.
⚠ Use low ≤ high so single-element ranges are checked.
When the search fails, low is the insert position.
⚠ Returning high would give the index before the insert slot.
Binary search for the last m with m² ≤ x.
⚠ x < 2 returns x directly.
Two biased binary searches.
⚠ A linear scan from one hit is O(n) in the worst case.
Identify the sorted half; test whether the target lies in it.
⚠ Use ≤ in nums[low] ≤ nums[mid] for two-element ranges.
nums[low] == nums[mid] == nums[high] ⇒ low++, high−−.
⚠ Duplicates make the worst case linear — that's unavoidable.
nums[mid] < nums[high] ⇒ high = mid, else low = mid + 1.
⚠ Compare with high, not low — comparing with low fails on an unrotated array.
Equal ⇒ high −= 1.
⚠ Don't jump high = mid on equality — the minimum could be between.
Climb toward the higher neighbour.
⚠ Checking the ends first keeps mid−1 and mid+1 in range.
Pair alignment (even, odd) flips after the single element.
⚠ Check the boundaries first so mid ± 1 is always valid.
Binary search on the answer (speed).
⚠ Use ceil — a partly eaten pile still costs a whole hour.
Binary search capacity in [max(w), sum(w)] with a greedy day count.
⚠ Packages must stay in order — no sorting.
Monotonic total ⇒ binary search on d.
⚠ The helper falls through to None when the total is too big — None is falsy, so it still works, but return False explicitly.
Bouquets(day) is monotonic ⇒ binary search the day.
⚠ Reset the run counter after forming a bouquet and on unbloomed flowers.
Binary search on the answer with a greedy feasibility check.
⚠ The low bound must be max(nums), not 0.
Treat the matrix as a flat sorted array.
⚠ Divide by the number of columns, not rows.
Staircase search from the bottom-left.
⚠ Starting at the top-left gives no information — both directions increase.
Binary search the partition: l1 ≤ r2 and l2 ≤ r1.
⚠ Search over the shorter array, or mid2 can go out of range.
missing(i) = arr[i] − (i + 1); answer = low + k.
⚠ The answer may be beyond the last element.
Per-key sorted list + binary search for floor(timestamp).
⚠ Remember the candidate when going right — that's the floor.
Slow / fast pointers.
⚠ The loop condition decides first vs second middle.
Copy next's value, then skip next.
⚠ Works only because the node is never the tail.
Dummy node; skip whole duplicate runs.
⚠ The dummy head handles duplicates at the very start.
Floyd: fast meets slow ⇔ cycle.
⚠ Compare nodes (identity), not values.
Meet, reset one to head, step together → cycle start.
⚠ Return null when phase 1 ends without meeting.
Gap of n between two pointers.
⚠ Removing the head is a special case without a dummy node.
prev ← temp ← front, one arrow at a time.
⚠ Save temp.next before overwriting it.
Detach [left, right], reverse, reconnect both ends.
⚠ left = 1 has no previous node — the head changes.
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.
Dummy head + pick the smaller node.
⚠ Use ≤ to keep the merge stable.
Pairwise merging rounds — O(N log k).
⚠ Merging one by one into a growing list is O(N·k).
Middle → reverse second half → compare.
⚠ Restoring the list is good practice — callers may reuse it.
Two dummy chains, then concatenate.
⚠ Set temp2.next = None or the list may loop.
Switch heads at the end; equal path lengths make them meet.
⚠ Compare node identity, not values.
Interleave copies → set randoms → separate.
⚠ Restore the original list's next pointers.
Hash map + doubly linked list with sentinels.
⚠ Sentinel head and tail remove all null checks.
freq → OrderedDict buckets + min_freq.
⚠ Ties at the same frequency are broken by recency — hence the ordered buckets.
Split at the middle, sort halves, merge.
⚠ Cut the list at the middle (midPrev.next = None) or the recursion never ends.
Grade-school addition with a carry.
⚠ Keep looping for a final carry (999 + 1).
Depth returns to 0 ⇒ a primitive ends.
⚠ A depth counter alone (no stack) is enough and avoids extra memory.
Push openers; each closer must match the top.
⚠ Leftover openers like '((' make it invalid.
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 of directory names.
⚠ '...' is a valid directory name, not a parent reference.
Stack of [char, count]; pop at count k.
⚠ Rebuilding with += in a loop is fine here; ''.join is faster for big inputs.
Operands on a stack; operator pops two.
⚠ Pop order matters for − and /.
Stack saves (answer, sign) at each '('.
⚠ Step back one index after reading a multi-digit number.
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.
Make push expensive so the oldest item stays on top.
⚠ The amortised two-stack version makes pop O(1) amortised instead.
Push (value, min so far) pairs.
⚠ A single 'current min' variable can't recover the old min after a pop.
Controlled in-order traversal with a stack of left spines.
⚠ Flattening the whole tree up front uses O(n) memory instead of O(h).
Stop when a full rotation makes no progress.
⚠ Counting each preference type gives O(n): stop when the top sandwich type has no takers.
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 increasing stack; pop larger previous digits while k > 0.
⚠ Leftover k comes off the end (the stack is increasing there).
Monotonic stack; width = i − stack_top − 1 when popping.
⚠ The −1 sentinel gives the correct width at the left edge.
Row-by-row histograms + largest-rectangle-in-histogram.
⚠ The −1 sentinel on the stack makes the width formula work at the left edge.
Left → node → right.
⚠ An explicit stack avoids recursion limits on very deep trees.
Node → left → right.
⚠ Iteratively, push right before left so left is processed first.
Left → right → node.
⚠ Iterative post-order is the trickiest of the three — reversed (node, right, left) is a neat shortcut.
depth = 1 + max(depth(left), depth(right)).
⚠ BFS by levels gives the same answer iteratively.
Swap children at every node.
⚠ Order doesn't matter — pre-order swapping works too.
Compare roots and recurse in lockstep.
⚠ Check the None cases before reading .val.
Mirror check: outer with outer, inner with inner.
⚠ Compare cross-wise, not left-with-left.
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²).
Pass the path maximum down.
⚠ Use ≥ — equal values count as good.
Reduce the target; check at leaves.
⚠ Only leaf-to-root paths count — an internal node hitting zero isn't enough.
Carry the path's digits; add at leaves.
⚠ path·10 + val avoids string building.
BFS with a level marker.
⚠ `node is "\n"` relies on string interning; == is the safe comparison.
BFS + flip direction per level.
⚠ unshift / insert(0) is O(k); a deque per level avoids it.
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.
Level-order BFS; next = following node in the level.
⚠ The perfect-tree version can be done in O(1) space using the next pointers of the level above.
Map column → row → sorted values.
⚠ Ties at the same row and column are broken by value, not left/right.
left + right + self ≥ 2 ⇒ LCA.
⚠ A node can be its own ancestor (p is the ancestor of q).
Root = middle element; recurse on halves.
⚠ Either middle works for even lengths; the tests accept any balanced BST.
Walk down until p and q split.
⚠ An iterative loop uses O(1) space.
Pass (min, max) bounds down the tree.
⚠ Comparing only with the direct parent misses violations deeper down (example 2).
In-order traversal → index k−1.
⚠ Stopping the traversal after k nodes makes it O(h + k).
Search for the value; attach at the first empty slot.
⚠ The cleaner form is root.left = insert(root.left, val).
Replace with successor/predecessor, then delete that one.
⚠ Reassign root.left / root.right with the recursive result.
Root from preorder; split sizes from inorder.
⚠ Values must be unique for the index map to work.
Root = postorder[end]; split by in-order index.
⚠ Careful with the post-order ranges — the root sits at the end.
Pre-order index + upper bound recursion.
⚠ Inserting values one by one is O(n²) for sorted input.
Recursion returns the tail of each flattened subtree.
⚠ The function must still return a tail even though the API says None.
Level-order with null markers; rebuild with a parent queue.
⚠ Empty tree ↔ empty string.
diameter = max over nodes of (left height + right height).
⚠ The path doesn't have to pass through the root.
State (node, can_rob); robbing forbids the children.
⚠ Returning a (rob, skip) pair per node avoids the memo dictionary entirely.
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.
Max-heap of size k on squared distance.
⚠ Comparing squared distances avoids floating-point roots.
Min-heap of size k; top = kth largest.
⚠ Shift by −min so negative values index correctly.
Counter + size-k min-heap on frequency.
⚠ Bucket sort by frequency gives O(n).
bisect to x, then expand the closer side.
⚠ Ties go to the smaller element (the left side).
Two heaps: max-heap low half, min-heap high half.
⚠ Python only has min-heaps — store negatives for the max-heap.
Sort by capital; max-heap of affordable profits.
⚠ Unaffordable projects aren't discarded — they may become affordable later.
Best-first walk over the (i, j) grid with a min-heap.
⚠ Without the seen set, (i+1, j+1) gets pushed twice.
Max-heap of counts + cooldown queue.
⚠ The formula (maxCount − 1)·(n + 1) + #maxCount gives the answer in O(T) without simulating.
5^ceil(n/2) · 4^floor(n/2) mod 1e9+7.
⚠ n can be 10¹⁵ — exponentiation by squaring is required.
Record at every node; extend with later indices.
⚠ Record a copy (subs[:]) — the list keeps changing.
Sort; skip nums[i] == nums[i−1] when i > index.
⚠ The condition is i != index (same level), not i > 0.
Backtrack with a start index; stop at size k.
⚠ Pruning when not enough numbers remain (n − i + 1 < k − len) speeds it up.
Recurse with the same index to allow reuse.
⚠ Starting the loop at start (not 0) prevents permutations of the same combination.
Sort; skip same-level duplicates; break on overshoot.
⚠ Break, don't continue — every later candidate is even bigger.
Backtrack over 1..9 with count and sum checks.
⚠ The duplicate check is harmless here — digits are already unique.
One recursion level per digit.
⚠ Empty input must return [] rather than [''].
Fix position start, swap each choice into it.
⚠ `num not in ds` costs O(n) and breaks with duplicate values.
Backtrack over a frequency map, not over indices.
⚠ Iterating the Counter keys means each value is tried once per level.
Factorial number system: index = k // fact.
⚠ Convert k to 0-based first.
Add '(' if left < n; add ')' if right < left.
⚠ Never let closes exceed opens.
Backtracking over palindromic prefixes; a dp table can remember which substrings are palindromes.
⚠ Append a copy (parts[:]) — the list keeps changing.
Column-by-column backtracking with row + diagonal hashes.
⚠ Only check to the left — columns to the right are still empty.
Backtracking that returns the number of solutions.
⚠ The board array isn't needed for counting — the hashes are enough.
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 DFS with a path-visited set.
⚠ Un-mark on the way back so other paths can reuse the cell.
Sort both; smallest sufficient cookie per child.
⚠ Skip cookies that are too small rather than skipping children.
Greedy over values including subtractive pairs.
⚠ Without CM, XC, IV, etc. you'd produce 'VIIII'.
Move the goal left whenever i + nums[i] ≥ goal.
⚠ A zero only matters if nothing before it can jump past it.
Implicit BFS over index windows.
⚠ Already at the end (n = 1) means 0 jumps.
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.
Two passes, take the max.
⚠ Equal ratings don't need more candy.
Extend consecutive runs.
⚠ Empty input returns [].
Three phases: before, overlap-merge, after.
⚠ Touching intervals ([1,2] and [2,3]) overlap.
Sort by end; count overlaps with the last kept.
⚠ Sorting by start instead needs extra logic to keep the smaller end.
Sort by end; new arrow when start > current end.
⚠ Touching balloons ([1,2] and [2,3]) share one arrow — use strict >.
original → copy map as both cache and visited set.
⚠ Store the copy before recursing, or cycles loop forever.
Count DFS launches from unvisited land.
⚠ Deep recursion on huge grids — BFS or marking the grid in place avoids it.
DFS through cells of the starting colour.
⚠ If the new colour equals the old one, a visited set (or early return) prevents infinite loops.
BFS from room 0 over key edges.
⚠ A key to an already-visited room is ignored.
Flood from the border, count the rest.
⚠ Think in reverse — find what escapes, not what's trapped.
DFS from 0 on the undirected graph; count edges pointing away.
⚠ Count edges by their original direction, not the direction you travel.
Mark border-connected O's, flip the rest.
⚠ Searching from interior O's is much harder — start from the border.
Count connected components with DFS.
⚠ The matrix is symmetric — no need to look at both triangles specially.
Multi-source BFS from every 0.
⚠ A BFS per 1-cell would be O((mn)²).
Multi-source BFS from land; answer = last distance.
⚠ Manhattan distance on a grid equals BFS steps.
Height = BFS distance from water.
⚠ Water cells must stay 0.
Multi-source BFS from rotten oranges; check none stay fresh.
⚠ No fresh oranges at all → 0 minutes.
BFS over one-letter mutations in the bank.
⚠ Use a set for the bank — list membership is O(B).
BFS from the entrance until a border cell.
⚠ The entrance doesn't count as an exit even if it's on the border.
BFS over squares; zig-zag coordinate conversion.
⚠ Only follow one snake/ladder per move (no chaining).
BFS 2-colouring per component.
⚠ The graph can be disconnected — start a BFS from every uncoloured node.
Cycle detection with path-visited markers.
⚠ visited alone isn't enough — a node finished in another branch isn't a cycle.
DFS post-order, reversed = topological order.
⚠ Many orders are valid — any topological order is accepted.
Three-colour DFS; safe = finished without touching the path.
⚠ Leave unsafe nodes at state 1 — that's what marks them.
Weighted graph; multiply along a BFS path.
⚠ x / x is 1 only if x appears in some equation.
BFS generating one-letter neighbours; remove words once used.
⚠ Removing words from the set doubles as the visited set.
BFS for levels, then DFS backwards along level − 1.
⚠ Searching backwards avoids exploring dead branches.
Dijkstra from k; answer = max distance.
⚠ Nodes are 1-indexed; ignore dist[0].
Dijkstra + ways: faster ⇒ copy ways, equal ⇒ add ways (mod 1e9+7).
⚠ Take the modulo when adding counts.
Dijkstra with max() instead of +.
⚠ Binary search on the effort + BFS is an alternative.
O(n³) · O(n²)Floyd–Warshall, then count reachable cities.
⚠ Use ≤ so later (larger) cities win ties.
Kruskal: sorted edges + union-find.
⚠ Prim's with a heap avoids storing all n² edges.
Min-heap of max-height-so-far along the path.
⚠ Binary search on time + BFS also works.
Union accounts sharing an email.
⚠ Names can repeat across different people — only shared emails merge accounts.
DSU sizes + try flipping each 0.
⚠ Use a set of neighbour roots so the same island isn't counted twice.
answer = stones − components (union row with column).
⚠ Count only nodes that actually appear in some stone.
Count extra edges and components with DSU.
⚠ Fewer than n − 1 cables total means −1 immediately.
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.
Bridge if low[child] > tin[node].
⚠ Skip only the parent edge, not every visited neighbour.
Strictly increasing edges form a DAG ⇒ memoised DFS.
⚠ No visited set is needed — strict increase already prevents cycles.
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.
8-direction BFS with path length in dist.
⚠ The path length counts cells, not moves.
BFS reachability.
⚠ source == destination is trivially True.
DFS returns island size.
⚠ No land → 0.
Reverse BFS from each ocean; intersect.
⚠ Water flows downhill, so the reverse search climbs uphill.
ways(n) = ways(n-1) + ways(n-2), with ways(0) = ways(1) = 1.
⚠ Plain recursion without the memo is exponential.
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.
best(i) = max(nums[i] + best(i-2), best(i-1)).
⚠ A single house must return nums[0] before dp[1] is read.
Circle → max(rob_line(nums[1:]), rob_line(nums[:-1])).
⚠ With one house, slicing both ends would leave nothing — handle len == 1 first.
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.
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.
profit(i) = price[i] − min(prices[0..i]).
⚠ You must buy before you sell — max(prices) − min(prices) ignores order.
dfs(i, can_buy): selling moves to i+2 — that skipped day is the cooldown.
⚠ The cooldown applies after a sell, not after a buy.
Subtract the fee once per transaction, on the sell edge.
⚠ Charging the fee on both buy and sell double-counts it.
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.
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.
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).
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.
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).
Obstacle cell ⇒ dp = 0; otherwise dp = left + up.
⚠ A blocked start or finish must return 0.
row[c] = prev[c-1] + prev[c], edges are 1.
⚠ prev is only read for inner cells, so row 0 never touches it.
C(r, i+1) = C(r, i) · (r − i) / (i + 1).
⚠ Multiply before dividing so the integer division stays exact.
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.
Equal partition ⇔ a subset sums to total / 2 (and total must be even).
⚠ Only seed dp[0][nums[0]] when nums[0] ≤ target.
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: include ⇒ 1 + dp[same coin][amount − coin].
⚠ Greedy 'largest coin first' fails (e.g. coins [1,3,4], amount 6).
ways[i][a] = ways[i-1][a] + ways[i][a − coin].
⚠ Looping amounts outer and coins inner counts permutations, not combinations.
dp[x] = 1 + min(dp[x − s]) over squares s ≤ x.
⚠ Break out of the squares loop once a square exceeds x.
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.
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.
dp[end] = any(dp[start] and s[start:end] ∈ words).
⚠ Without memo, the recursive version explodes on inputs like 'aaaa…b'.
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.
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].
Once k-1 buckets are full, the remaining numbers must fill the last one.
⚠ Undo the 'taken' mark after each try (backtracking).
'*' ⇒ dp(i, j+1) or dp(i+1, j).
⚠ The 'string empty' base case must allow a run of trailing stars.
Backtracking over prefix words; a full path is one sentence.
⚠ Pop after recursing or later sentences inherit stale words.
deletions = (m − LCS) + (n − LCS).
⚠ Recognising the reduction to LCS is the whole problem.
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.
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.
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.
insertions = n − LPS(s).
⚠ Spotting the reduction to LPS is the key step.
LCS table, then reconstruct while emitting skipped characters.
⚠ Characters you'd skip for the LCS must still appear in the supersequence.
Sorted + 'divides' is transitive ⇒ it's LIS with % instead of <.
⚠ Sorting first is what makes checking only the last element enough.
O(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.
Patience sorting: tails stay sorted, so bisect_left finds where each number belongs.
⚠ Use bisect_left for strictly increasing; bisect_right allows equal values.
Longer ⇒ copy the count; equal ⇒ add the count.
⚠ Sum counts over every index that reaches the max length, not just the last one.
Sort (w ↑, h ↓), then LIS on heights.
⚠ Without height-descending on ties, [3,4] and [3,5] would wrongly nest.
Count expansions from 2n-1 centres.
⚠ Count every expansion, not just the longest one.
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 = 1 + min(up, left, diagonal); sum(dp) = number of squares.
⚠ Cells with 0 stay 0 — they end no square.
dp = 1 + min(up, left, diagonal); answer = max side².
⚠ The matrix holds characters '0'/'1', not integers.
Win ⇔ n is even.
⚠ n = 1 is a loss: no x with 0 < x < 1 exists.
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.
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.
count = 1 + count(left) + count(right).
⚠ Comparing left and right heights gives O(log² n) by using completeness.
Skip trailing spaces, count back to a space.
⚠ Trailing spaces are the trap.
Reverse half the digits and compare.
⚠ Converting to a string works but isn't the intended trick.
Carry propagation from the right.
⚠ [9,9,9] becomes [1,0,0,0].
Counter(magazine) ≥ Counter(note) letter by letter.
⚠ Each magazine letter can be used once.
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²).
Σ n // 5^i.
⚠ Computing n! directly overflows (and is slow) quickly.
BFS level by level; link to the queue front.
⚠ A None root still enters the queue — the `continue` handles it.
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.
Greedy packing + even/remainder space distribution.
⚠ Left gaps get the remainder, not the right ones.
BFS with level size; average per level.
⚠ Use floating-point division.
In-order with a previous-node pointer.
⚠ Comparing a node only with its children misses neighbours across subtrees.
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).
Meet in the middle: subset sums by size + binary search.
⚠ Sizes must add to n — that's why sums are grouped by count.
Merge sort; count cross pairs before each merge.
⚠ Count before merging — the halves must still be separate.
Post-order returning (sum, min, max) or 'not a BST'.
⚠ The best sum starts at 0 — an all-negative tree returns 0 (empty BST).