Practice tracker Every curated problem across all topics. Filter, pick a random unsolved one, and track what you’ve solved or need to revisit. Progress is stored in this browser — export it to move between devices.
0/414 total solved
0/74 easy
0/244 medium
0/96 hard
Showing 414 of 414
Big-O & Complexity Analysis
Compare the O(n^2) pairwise check, the O(n log n) sort-then-scan, and the O(n) hash set. Same problem, three complexity classes.
Easy
Big-O & Complexity Analysis
Naive recursion is O(2^n); memoization or iteration is O(n). Draw the recursion tree to see why.
Easy
Big-O & Complexity Analysis
Fast exponentiation halves n each step: O(log n). x^n = (x^(n/2))^2, times x if n is odd. Watch n = INT_MIN.
Medium
Big-O & Complexity Analysis
Sieve of Eratosthenes runs in O(n log log n) — a nice example of a non-obvious complexity bound.
Medium
Big-O & Complexity Analysis
Brute force is O(n^3) or O(n^2); Kadane's algorithm is O(n). Great exercise in shaving factors off.
Medium
Recursion & Divide and Conquer
swap(s[l], s[r]) then recurse on (l+1, r-1). Base case l >= r.
Easy
Recursion & Divide and Conquer
The smaller head wins; its next = merge(rest of its list, other list).
Easy
Recursion & Divide and Conquer
depth(node) = 1 + max(depth(left), depth(right)); depth(None) = 0.
Easy
Recursion & Divide and Conquer
half = pow(x, n//2); return half*half (times x if n odd). Handle negative n with 1/x.
Medium
Recursion & Divide and Conquer
Row n's k-th symbol comes from its parent at row n-1, position (k+1)//2; flip if k is even.
Medium
Recursion & Divide and Conquer
Split at every operator, recursively compute all results on each side, combine. Memoize on substring.
Medium
Recursion & Divide and Conquer
Implement merge sort: split, sort halves recursively, merge in O(n).
Medium
Recursion & Divide and Conquer
Merge sort on (value, index) pairs: when taking from the left half, add how many right-half elements already went before it.
Hard
Recursion & Divide and Conquer
Merge sort; before merging, count pairs i in left, j in right with a[i] > 2*a[j] using a moving pointer.
Hard
Hash Maps & Sets
Map value → index. For each x, check whether target − x is already in the map before inserting x.
Easy
Hash Maps & Sets
Counter(s) == Counter(t), or a 26-slot count array: +1 for s, −1 for t, all zeros at the end.
Easy
Hash Maps & Sets
Store the last index of each value; duplicate within k if i − last[x] <= k.
Easy
Hash Maps & Sets
Count magazine letters; decrement for each note letter; fail on a negative count.
Easy
Hash Maps & Sets
Canonical key = sorted word (or tuple of 26 counts). defaultdict(list) keyed by it.
Medium
Hash Maps & Sets
Count, then bucket sort by frequency (buckets 0..n) for O(n), or a size-k heap.
Medium
Hash Maps & Sets
Put all in a set. Only start counting from x if x−1 is not in the set, so each run is walked once: O(n).
Medium
Hash Maps & Sets
Prefix sum + hashmap of counts of previous prefixes; add count[prefix − k] at each step. Seed count[0] = 1.
Medium
Hash Maps & Sets
Sets per row, column and 3x3 box (index r//3*3 + c//3). Any repeat → invalid.
Medium
Hash Maps & Sets
Length-prefix each string, e.g. '5#hello'. Decoding reads digits up to '#', then that many chars.
Medium
Hash Maps & Sets
Meet in the middle: count all a+b sums in a map, then for each c+d add count[−(c+d)]. O(n^2).
Medium
Hash Maps & Sets
O(1) space: use the array itself as a hash — place value v at index v−1 by swapping, then find the first mismatch.
Hard
Sorting Algorithms
Fill nums1 from the back with the larger of the two tails, so you never overwrite unread values.
Easy
Sorting Algorithms
Two pointers at the ends; the larger absolute value goes to the end of the result.
Easy
Sorting Algorithms
Dutch national flag: low/mid/high pointers; 0 swaps to low, 2 swaps to high (don't advance mid), 1 advances mid.
Medium
Sorting Algorithms
Implement merge sort or heap sort (quicksort needs a random pivot to avoid TLE on adversarial input).
Medium
Sorting Algorithms
Custom comparator: a before b if a+b > b+a as strings. Edge case: all zeros → '0'.
Medium
Sorting Algorithms
Quickselect for O(n) average, or a size-k min-heap for O(n log k).
Medium
Sorting Algorithms
Sort descending; h is the largest i with citations[i-1] >= i. Or counting sort capped at n.
Medium
Sorting Algorithms
Radix sort, or pigeonhole buckets of size (max−min)/(n−1): the max gap is between buckets, not inside one.
Medium
Sorting Algorithms
Sort, then interleave the reversed smaller half and reversed larger half so equal medians don't touch.
Medium
Sorting Algorithms
Merge sort on prefix sums; during merge count right-half prefixes within [left + lower, left + upper] with two moving pointers.
Hard
Arrays, Strings & Matrices
Track the minimum price so far; answer is max(price − min_so_far).
Easy
Arrays, Strings & Matrices
Write pointer: copy every non-zero forward, then fill the rest with zeros (or swap in place).
Easy
Arrays, Strings & Matrices
Two pointers skipping non-alphanumerics, compare lowercase.
Easy
Arrays, Strings & Matrices
Compare column by column across all strings, stop at the first mismatch or shortest length.
Easy
Arrays, Strings & Matrices
Kadane: cur = max(x, cur + x); best = max(best, cur).
Medium
Arrays, Strings & Matrices
Prefix products left-to-right into the answer, then multiply by a running suffix product right-to-left.
Medium
Arrays, Strings & Matrices
k %= n; reverse all, reverse first k, reverse the rest.
Medium
Arrays, Strings & Matrices
Shrink four boundaries (top, bottom, left, right) after each side; check bounds before the bottom row and left column.
Medium
Arrays, Strings & Matrices
Transpose, then reverse each row (clockwise).
Medium
Arrays, Strings & Matrices
Use the first row/col as markers; remember separately whether row 0 / col 0 themselves need zeroing.
Medium
Arrays, Strings & Matrices
Track both max and min ending here; a negative number swaps them.
Medium
Arrays, Strings & Matrices
Read pointer finds each run; write pointer writes char then digits of count.
Medium
Arrays, Strings & Matrices
Encode old and new state in the same cell (e.g. bit 0 = old, bit 1 = new), then shift right.
Medium
Arrays, Strings & Matrices
Water at i = min(maxLeft, maxRight) − h[i]. Two pointers: move the side with the smaller max.
Hard
Linked Lists
prev = None; for each node: save next, point node.next to prev, advance prev and cur.
Easy
Linked Lists
Dummy head + tail pointer; attach the smaller node each time; attach the leftover list at the end.
Easy
Linked Lists
Floyd: slow moves 1, fast moves 2; they meet iff there's a cycle.
Easy
Linked Lists
When fast reaches the end, slow is at the middle.
Easy
Linked Lists
Find middle, reverse second half, compare the halves (optionally restore).
Easy
Linked Lists
Dummy head; move fast n+1 ahead, then move both until fast is null; slow.next is the target.
Medium
Linked Lists
After slow and fast meet, restart one pointer at head; moving both by 1, they meet at the cycle entrance.
Medium
Linked Lists
Split at middle, reverse second half, interleave the two halves.
Medium
Linked Lists
Digits are reversed, so add node by node with a carry; continue while either list or carry remains.
Medium
Linked Lists
Hash map old → new node, two passes. O(1) space: interleave copies A→A'→B→B', set randoms, then unweave.
Medium
Linked Lists
Treat i → nums[i] as next pointers; the duplicate is the cycle entrance (Floyd).
Medium
Linked Lists
Merge sort: split with slow/fast, sort halves, merge. O(n log n).
Medium
Linked Lists
Hash map key → node in a doubly linked list; move to front on access, evict from the back.
Medium
Linked Lists
Check k nodes exist, reverse that segment, connect prev-group tail to new head, repeat.
Hard
Linked Lists
Min-heap of current heads (tie-break by index), or pairwise merge in log k rounds.
Hard
Stacks, Queues & Monotonic Structures
Push openers; on a closer, the top must be its matching opener. Stack must be empty at the end.
Easy
Stacks, Queues & Monotonic Structures
Inbox and outbox stacks; pour inbox into outbox only when outbox is empty. Amortized O(1).
Easy
Stacks, Queues & Monotonic Structures
Store (value, min so far) pairs on the stack.
Medium
Stacks, Queues & Monotonic Structures
Push numbers; on an operator pop b then a, push a op b. Truncate division toward zero.
Medium
Stacks, Queues & Monotonic Structures
Monotonic decreasing stack of indices; a warmer day pops and answers all colder days.
Medium
Stacks, Queues & Monotonic Structures
Circular array: iterate i from 0 to 2n−1 using i % n, only push during the first pass.
Medium
Stacks, Queues & Monotonic Structures
On '[' push (current string, repeat count); on ']' pop and set cur = prev + cur * count.
Medium
Stacks, Queues & Monotonic Structures
Stack of survivors; a left-moving asteroid fights right-moving tops until it dies or wins.
Medium
Stacks, Queues & Monotonic Structures
Stack of (price, span); pop all prices <= today and add their spans.
Medium
Stacks, Queues & Monotonic Structures
Sort by position descending; compute arrival times; a new fleet forms when time exceeds the stack top.
Medium
Stacks, Queues & Monotonic Structures
Each a[i] is the min of (i − prevLess) × (nextLessOrEqual − i) subarrays; find both with monotonic stacks.
Medium
Stacks, Queues & Monotonic Structures
Greedy increasing stack: pop a larger previous digit while k > 0; strip leading zeros.
Medium
Stacks, Queues & Monotonic Structures
Increasing stack; when a bar pops, its width spans from the new top+1 to i−1.
Hard
Stacks, Queues & Monotonic Structures
Deque of indices with decreasing values; drop the front when it leaves the window.
Hard
Stacks, Queues & Monotonic Structures
Running result and sign; on '(' push (result, sign) and reset; on ')' combine with the popped pair.
Hard
Stacks, Queues & Monotonic Structures
Build a histogram of consecutive 1s per row and run Largest Rectangle in Histogram on each row.
Hard
Two Pointers
Opposite ends; skip non-alphanumerics; compare case-insensitively.
Easy
Two Pointers
Sum too small → move left right; too big → move right left.
Easy
Two Pointers
Write pointer; copy nums[i] only when it differs from nums[write−1].
Easy
Two Pointers
Pointer into s advances only on a match while scanning t.
Easy
Two Pointers
Sort; fix i, two-pointer the rest for −nums[i]; skip duplicate values at i, l and r.
Medium
Two Pointers
Opposite ends; always move the shorter wall — the taller one can't improve with less width.
Medium
Two Pointers
Same as 3Sum but track the sum with the smallest |sum − target|.
Medium
Two Pointers
Three pointers (Dutch national flag).
Medium
Two Pointers
Sort; pair the heaviest with the lightest if they fit, else the heaviest goes alone.
Medium
Two Pointers
Two nested fixed indices + two pointers, O(n^3); skip duplicates at every level.
Medium
Two Pointers
Record each char's last index; extend the current part's end to max(last[c]); cut when i == end.
Medium
Two Pointers
Pointers at both ends with leftMax/rightMax; the side with the smaller max is settled.
Hard
Sliding Window
Fixed window of size k: add the incoming element, subtract the outgoing one.
Easy
Sliding Window
Window from the lowest price seen so far to today.
Easy
Sliding Window
Expand right; while the new char is duplicated in the window, shrink left. Or jump left to last[c]+1.
Medium
Sliding Window
Window valid while (length − maxFreq) <= k. maxFreq never needs to decrease.
Medium
Sliding Window
Fixed window of len(s1) over s2; compare 26-count arrays (or track number of matching letters).
Medium
Sliding Window
Same as Permutation in String, but collect every start index.
Medium
Sliding Window
Positive numbers: expand until sum >= target, then shrink while valid recording min length.
Medium
Sliding Window
Longest window containing at most k zeros.
Medium
Sliding Window
Longest window with at most 2 distinct values.
Medium
Sliding Window
Shrink while product >= k; each right end adds (right − left + 1) valid subarrays.
Medium
Sliding Window
exactly(goal) = atMost(goal) − atMost(goal − 1).
Medium
Sliding Window
Need-count map + 'formed' counter; expand until all satisfied, then shrink recording the best window.
Hard
Sliding Window
atMost(K) − atMost(K−1) where atMost counts windows with <= K distinct values.
Hard
Sliding Window
Monotonic deque of indices with decreasing values.
Hard
Prefix Sums & Difference Arrays
prefix[i] = prefix[i−1] + nums[i].
Easy
Prefix Sums & Difference Arrays
prefix of length n+1; sum(l..r) = P[r+1] − P[l].
Easy
Prefix Sums & Difference Arrays
Left sum == total − left sum − nums[i].
Easy
Prefix Sums & Difference Arrays
Hash map of prefix counts; add count[P − k]; seed count[0] = 1.
Medium
Prefix Sums & Difference Arrays
Store first index of each prefix mod k; same remainder at distance >= 2 → yes.
Medium
Prefix Sums & Difference Arrays
Count prefixes by remainder (normalize negatives); pairs with equal remainder.
Medium
Prefix Sums & Difference Arrays
Map 0 → −1; longest subarray with sum 0 = earliest index of each prefix value.
Medium
Prefix Sums & Difference Arrays
2D prefix with inclusion–exclusion.
Medium
Prefix Sums & Difference Arrays
Difference array: diff[l] += x, diff[r+1] −= x, then prefix-sum.
Medium
Prefix Sums & Difference Arrays
Difference array over locations; running sum must never exceed capacity.
Medium
Prefix Sums & Difference Arrays
Prefix products times suffix products.
Medium
Prefix Sums & Difference Arrays
Earliest index of each prefix; length = i − first[P − k].
Medium
Prefix Sums & Difference Arrays
Negatives allowed: monotonic increasing deque of prefix indices; pop front while P[i] − P[front] >= k.
Hard
Prefix Sums & Difference Arrays
Count pairs of prefixes with P[j] − P[i] in [lower, upper] via merge sort or a Fenwick tree.
Hard
Binary Search
Classic: lo=0, hi=n−1, while lo <= hi.
Easy
Binary Search
First index with nums[i] >= target (lower_bound).
Easy
Binary Search
First true of a monotone predicate.
Easy
Binary Search
Last m with m*m <= x.
Easy
Binary Search
lower_bound(target) and lower_bound(target+1) − 1.
Medium
Binary Search
Treat as a flat sorted array: index i → (i // C, i % C).
Medium
Binary Search
Compare nums[mid] with nums[hi]: if bigger, min is right of mid; else at mid or left.
Medium
Binary Search
One half is sorted; check whether target is inside it and discard the other half.
Medium
Binary Search
If nums[mid] < nums[mid+1], a peak exists to the right; else at mid or left.
Medium
Binary Search
Binary search the speed; feasible if sum(ceil(p/speed)) <= h.
Medium
Binary Search
Answer in [max(w), sum(w)]; greedy count of days for a capacity is monotone.
Medium
Binary Search
Per key, timestamps are increasing; bisect_right for the last timestamp <= t.
Medium
Binary Search
Binary search the day; count bouquets of k adjacent bloomed flowers.
Medium
Binary Search
Binary search the max sum; greedily count pieces needed; feasible if pieces <= k.
Hard
Binary Search
Binary search the partition in the shorter array so that left halves' maxima <= right halves' minima.
Hard
Binary Search
Binary search distance d; count pairs with distance <= d via two pointers on the sorted array.
Hard
Backtracking
At each index choose include/skip, or loop start..n adding each partial path to the result.
Medium
Backtracking
Sort; in the loop skip nums[i] == nums[i−1] when i > start.
Medium
Backtracking
used[] array; each level picks any unused element.
Medium
Backtracking
Sort; skip nums[i] if equal to nums[i−1] and nums[i−1] is not used.
Medium
Backtracking
Loop i from start to n; prune when remaining numbers < slots left.
Medium
Backtracking
Reuse allowed → recurse with i (not i+1); sort and break when candidate > remaining.
Medium
Backtracking
Each used once → recurse with i+1; skip duplicates at the same level.
Medium
Backtracking
One level per digit; branch over its letters.
Medium
Backtracking
Add '(' if open < n; add ')' if close < open.
Medium
Backtracking
At start, try every end where s[start..end] is a palindrome (precompute isPal table).
Medium
Backtracking
DFS from each cell; mark visited by overwriting the cell, restore on return.
Medium
Backtracking
4 levels, each takes 1–3 digits in 0..255 without leading zeros; prune on remaining length.
Medium
Backtracking
Sort descending, fill buckets; skip a bucket whose sum equals a previously tried bucket.
Medium
Backtracking
One queen per row; sets for columns, r−c diagonals and r+c anti-diagonals.
Hard
Backtracking
Try digits in each empty cell with row/col/box sets; choose the cell with fewest options first for speed.
Hard
Backtracking
Build a trie of words; DFS the board walking the trie; prune dead trie branches.
Hard
Greedy Algorithms
Sort both; give each child the smallest cookie that satisfies them.
Easy
Greedy Algorithms
Simulate; for $20 prefer giving $10+$5 over three $5s.
Easy
Greedy Algorithms
Sum every positive day-to-day difference.
Medium
Greedy Algorithms
Track farthest reachable; fail if i > farthest.
Medium
Greedy Algorithms
BFS by levels: current range end and farthest; jump when i reaches the current end.
Medium
Greedy Algorithms
If total gas >= total cost an answer exists; reset the start whenever the running tank goes negative.
Medium
Greedy Algorithms
Extend the current part to the last occurrence of every char in it.
Medium
Greedy Algorithms
Always start a group from the smallest remaining card; use a counter + sorted keys.
Medium
Greedy Algorithms
Sort by end; keep an interval if it starts after the last kept end; remove the rest.
Medium
Greedy Algorithms
Answer = max(len(tasks), (maxFreq − 1)(n + 1) + countOfMaxFreq).
Medium
Greedy Algorithms
Track the range [lo, hi] of possible open counts; clamp lo at 0; fail if hi < 0.
Medium
Greedy Algorithms
Sort by end; shoot at the first end; skip every balloon starting at or before it.
Medium
Greedy Algorithms
Left-to-right pass for left neighbours, right-to-left for right neighbours; take the max.
Hard
Greedy Algorithms
Sort projects by capital; push affordable ones into a max-heap of profit; take the best k times.
Hard
Greedy Algorithms
Drive as far as possible; when stuck, retroactively refuel at the biggest station passed (max-heap).
Hard
Intervals & Sweep Line
Sort by start; any start < previous end means a conflict.
Easy
Intervals & Sweep Line
Extend a run while the next number is +1; emit 'a->b' or 'a'.
Easy
Intervals & Sweep Line
Sort by start; if the next starts <= last end, extend the end; else append.
Medium
Intervals & Sweep Line
Three phases: add those ending before, merge the overlapping ones, add the rest.
Medium
Intervals & Sweep Line
Sort by end; count kept intervals greedily; removals = n − kept.
Medium
Intervals & Sweep Line
Min-heap of end times, or sweep +1/−1 events sorted with ends before starts at ties.
Medium
Intervals & Sweep Line
Two pointers; intersection is [max starts, min ends] if valid; advance the one that ends first.
Medium
Intervals & Sweep Line
Sort by end; greedy arrows at each uncovered end.
Medium
Intervals & Sweep Line
Sorted structure of intervals; check the neighbours around the insertion point.
Medium
Intervals & Sweep Line
Sweep: +passengers at from, −passengers at to; running total <= capacity.
Medium
Intervals & Sweep Line
Sort intervals and queries; push intervals with start <= q into a heap by size; pop those ending before q.
Hard
Intervals & Sweep Line
Flatten and merge all intervals; gaps between merged intervals are free time.
Hard
Intervals & Sweep Line
Sweep x-coordinates; max-heap of active heights (lazy deletion); emit when the max changes.
Hard
Bit Manipulation
XOR of all numbers; pairs cancel out.
Easy
Bit Manipulation
n &= n − 1 clears the lowest set bit; count iterations.
Easy
Bit Manipulation
bits[i] = bits[i >> 1] + (i & 1).
Easy
Bit Manipulation
XOR all indices 0..n with all values; the leftover is missing.
Easy
Bit Manipulation
32 times: result = (result << 1) | (n & 1); n >>= 1.
Easy
Bit Manipulation
n > 0 and n & (n − 1) == 0.
Easy
Bit Manipulation
sum = a ^ b, carry = (a & b) << 1; repeat until carry is 0 (mask to 32 bits in Python).
Medium
Bit Manipulation
Count each bit position mod 3; or the ones/twos state machine.
Medium
Bit Manipulation
XOR all = a ^ b; split numbers by its lowest set bit; XOR each group.
Medium
Bit Manipulation
Common binary prefix of left and right: shift both right until equal, then shift back.
Medium
Bit Manipulation
Binary trie from the high bit; for each number greedily walk the opposite bit.
Medium
Bit Manipulation
Every mask 0..2^n − 1 is a subset.
Medium
Bit Manipulation
Per bit: if c bit is 1 need at least one set (1 flip if neither); if 0, flip every set bit.
Medium
Heaps & Priority Queues
Min-heap of size k; the root is the k-th largest.
Easy
Heaps & Priority Queues
Max-heap simulation: pop two, push the difference if non-zero.
Easy
Heaps & Priority Queues
Size-k min-heap: O(n log k). Or quickselect.
Medium
Heaps & Priority Queues
Count, then heap by frequency (or bucket sort).
Medium
Heaps & Priority Queues
Max-heap of size k keyed by squared distance.
Medium
Heaps & Priority Queues
Max-heap of counts + cooldown queue simulation (or the counting formula).
Medium
Heaps & Priority Queues
Always place the most frequent char that isn't the previous one; hold the previous aside for one step.
Medium
Heaps & Priority Queues
Heap seeded with (nums1[i] + nums2[0]); popping (i, j) pushes (i, j+1).
Medium
Heaps & Priority Queues
K-way merge of rows with a heap, or binary search on value with a staircase count.
Medium
Heaps & Priority Queues
Sort by enqueue time; heap of available tasks by (processing time, index); jump time when idle.
Medium
Heaps & Priority Queues
Heap of (value, list index, node).
Hard
Heaps & Priority Queues
Max-heap for the low half, min-heap for the high half; rebalance so sizes differ by at most 1.
Hard
Heaps & Priority Queues
Two heaps with lazy deletion (hash map of pending removals), or a sorted list.
Hard
Heaps & Priority Queues
Heap holds one element per list; track the current max; pop min and advance that list.
Hard
Binary Trees
Swap children, recurse on both.
Easy
Binary Trees
1 + max(depth(left), depth(right)).
Easy
Binary Trees
Both null → true; one null or values differ → false; else recurse on both sides.
Easy
Binary Trees
For each node check sameTree(node, sub).
Easy
Binary Trees
Height DFS; update global best with leftHeight + rightHeight at every node.
Easy
Binary Trees
Return height, or −1 as a 'not balanced' sentinel that propagates up.
Easy
Binary Trees
BFS; process len(queue) nodes per level.
Medium
Binary Trees
BFS and take the last node of each level (or DFS right-first, record first visit per depth).
Medium
Binary Trees
Pass the max value on the path down; node is good if val >= max.
Medium
Binary Trees
Prefix sums along the root-to-node path in a hash map; undo on the way back up.
Medium
Binary Trees
If node is p or q return it; if both subtrees return non-null, node is the LCA.
Medium
Binary Trees
Preorder's first is the root; its inorder index splits left/right sizes. Hash inorder positions.
Medium
Binary Trees
Reverse post-order (right, left, root) with a 'prev' pointer; or Morris-style rewiring.
Medium
Binary Trees
Add parent pointers, then BFS from the target k steps as an undirected graph.
Medium
Binary Trees
Return max downward gain max(0, ...) to the parent; update global with left + node + right.
Hard
Binary Trees
Preorder with '#' for nulls; deserialize by consuming tokens recursively.
Hard
Binary Trees
Post-order states: 0 = needs cover, 1 = has camera, 2 = covered. Place a camera if any child needs cover.
Hard
Binary Search Trees
Go left if target < val, right if greater.
Easy
Binary Search Trees
Walk down: both smaller → left, both larger → right, else current node.
Medium
Binary Search Trees
Middle element is the root; recurse on halves.
Easy
Binary Search Trees
In-order gives sorted values; compare adjacent ones.
Easy
Binary Search Trees
Pass (low, high) bounds down; or check in-order is strictly increasing.
Medium
Binary Search Trees
Iterative in-order; stop at the k-th popped node.
Medium
Binary Search Trees
Walk to the null spot where the value belongs and attach a new node.
Medium
Binary Search Trees
0/1 child: splice out. 2 children: copy the in-order successor's value, delete the successor.
Medium
Binary Search Trees
Controlled in-order with a stack of left spines: O(h) memory, O(1) amortized next.
Medium
Binary Search Trees
Hash set during traversal, or two BST iterators (forward and backward) as two pointers.
Easy
Binary Search Trees
If node < low return trim(right); if > high return trim(left); else trim both children.
Medium
Binary Search Trees
In-order finds the one or two inversions; swap the first bad 'prev' with the last bad 'cur'.
Medium
Binary Search Trees
Ordered set of the last k values; check the successor of x − t is <= x + t. Or buckets of size t+1.
Hard
Tries (Prefix Trees)
Node = children map + is_end flag. search checks is_end; startsWith doesn't.
Medium
Tries (Prefix Trees)
Trie; on '.', DFS into every child.
Medium
Tries (Prefix Trees)
Insert roots; for each word walk the trie and stop at the first is_end.
Medium
Tries (Prefix Trees)
Trie; DFS only through nodes that are word ends; track the longest (lexicographically smallest).
Medium
Tries (Prefix Trees)
Trie with up to 3 sorted words stored per node; or sort + binary search per prefix.
Medium
Tries (Prefix Trees)
Each node stores the sum of values below it; update with the delta when a key is overwritten.
Medium
Tries (Prefix Trees)
Binary trie; greedily take the opposite bit from the top.
Medium
Tries (Prefix Trees)
Trie of words + grid DFS; store the word at its end node; prune leaves after finding them.
Hard
Tries (Prefix Trees)
Trie of reversed words; for each word check the remaining suffix/prefix is a palindrome.
Hard
Tries (Prefix Trees)
Sort by length; word-break DP using a trie (or set) of shorter words.
Hard
Graph Traversal (BFS, DFS, Topological Sort)
DFS/BFS from the start cell recoloring cells of the original color (return early if same color).
Easy
Graph Traversal (BFS, DFS, Topological Sort)
BFS/DFS from source, or Union-Find.
Easy
Graph Traversal (BFS, DFS, Topological Sort)
Each unvisited '1' starts a DFS that sinks its whole island; count starts.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
DFS returns the size of the component.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
Hash map old → clone; DFS/BFS creating clones on first visit.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
Multi-source BFS from all rotten oranges; count levels; check no fresh remain.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
Multi-source BFS from every 0.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
Reverse the flow: DFS uphill from each ocean's border; answer is the intersection.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
Mark 'O's connected to the border as safe; flip all others.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
Kahn's algorithm: can finish iff all nodes get processed (no cycle).
Medium
Graph Traversal (BFS, DFS, Topological Sort)
Return Kahn's processing order (empty if a cycle exists).
Medium
Graph Traversal (BFS, DFS, Topological Sort)
2-color with BFS/DFS; a neighbour with the same color means not bipartite. Graph may be disconnected.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
DFS from room 0; check all rooms visited.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
BFS with 8 directions; path length counts cells.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
BFS over 10^4 states; each state has 8 neighbours; deadends are pre-visited.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
3-color DFS: nodes that finish black without hitting a gray node are safe. Or Kahn on the reversed graph.
Medium
Graph Traversal (BFS, DFS, Topological Sort)
BFS over words; generate neighbours with wildcard patterns like h*t → bucket map.
Hard
Graph Traversal (BFS, DFS, Topological Sort)
First differing char of adjacent words gives an edge; topo sort; invalid if a word is a prefix of a previous longer one.
Hard
Graph Traversal (BFS, DFS, Topological Sort)
BFS over (node, visited mask) states, starting from every node at once.
Hard
Shortest Paths
Dijkstra from k; answer is the max distance (or −1 if unreachable).
Medium
Shortest Paths
Dijkstra where path cost = max edge on the path (minimax); or binary search + BFS.
Medium
Shortest Paths
Bellman-Ford for k+1 rounds, copying the distance array each round.
Medium
Shortest Paths
Dijkstra with a max-heap maximizing the product of probabilities.
Medium
Shortest Paths
Floyd-Warshall (n <= 100), count reachable within threshold.
Medium
Shortest Paths
0-1 BFS: following the arrow costs 0, other directions cost 1.
Hard
Shortest Paths
Minimax path: Dijkstra with cost = max elevation on the path.
Hard
Shortest Paths
Dijkstra that also counts ways: equal distance → add ways; shorter → replace.
Medium
Shortest Paths
0-1 BFS: entering an obstacle costs 1, empty costs 0.
Hard
Shortest Paths
BFS over (r, c, eliminations left) states.
Hard
Shortest Paths
BFS/Dijkstra keeping the best two distinct distances per node.
Hard
Union-Find (Disjoint Set Union)
Union every connected pair; count distinct roots (or decrement a counter per successful union).
Medium
Union-Find (Disjoint Set Union)
The first edge whose endpoints already share a root closes a cycle.
Medium
Union-Find (Disjoint Set Union)
Exactly n−1 edges and no union fails.
Medium
Union-Find (Disjoint Set Union)
components = n − successful unions.
Medium
Union-Find (Disjoint Set Union)
Union emails within each account (map email → id); group emails by root; sort.
Medium
Union-Find (Disjoint Set Union)
Union row r with column (c + offset); answer = stones − components.
Medium
Union-Find (Disjoint Set Union)
Union all '==' first; then any '!=' within one set is a contradiction.
Medium
Union-Find (Disjoint Set Union)
Weighted union-find storing ratio to parent; or BFS/DFS on a weighted graph.
Medium
Union-Find (Disjoint Set Union)
Indices in one component can be permuted freely; sort characters within each component.
Medium
Union-Find (Disjoint Set Union)
Add land cells online; each new cell +1 island, each successful union with a neighbour −1.
Hard
Union-Find (Disjoint Set Union)
Union x with x+1 when present; largest component size (a set-based solution also works).
Medium
Union-Find (Disjoint Set Union)
Add cells in increasing elevation, union with lower neighbours; stop when corners connect.
Hard
Union-Find (Disjoint Set Union)
Offline: sort queries by limit and edges by weight; add edges < limit, then check find(u) == find(v).
Hard
MST & Advanced Graph Algorithms
Complete graph with Manhattan weights: Prim's O(n^2) without a heap is ideal.
Medium
MST & Advanced Graph Algorithms
Kruskal: sort edges, union; −1 if fewer than n−1 edges were used.
Medium
MST & Advanced Graph Algorithms
Add a virtual node 0 with edges of cost wells[i]; MST of the augmented graph.
Hard
MST & Advanced Graph Algorithms
Critical: MST weight increases without it. Pseudo: forcing it in keeps the MST weight.
Hard
MST & Advanced Graph Algorithms
Tarjan bridges: edge (u, v) is a bridge if low[v] > disc[u].
Hard
MST & Advanced Graph Algorithms
Hierholzer's Eulerian path with lexicographically sorted adjacency; append on backtrack, reverse.
Hard
MST & Advanced Graph Algorithms
Eulerian path starting at the node with out − in = 1 (Hierholzer).
Hard
MST & Advanced Graph Algorithms
Binary lifting: up[j][v] = up[j−1][up[j−1][v]]; decompose k into bits.
Hard
MST & Advanced Graph Algorithms
Each node has out-degree <= 1: walk from each unvisited node with timestamps to measure cycles.
Hard
Dynamic Programming Fundamentals
ways(n) = ways(n−1) + ways(n−2).
Easy
Dynamic Programming Fundamentals
Two rolling variables.
Easy
Dynamic Programming Fundamentals
dp[i] = cost[i] + min(dp[i−1], dp[i−2]); answer min of the last two.
Easy
Dynamic Programming Fundamentals
Three rolling variables.
Easy
Dynamic Programming Fundamentals
row[j] = prev[j−1] + prev[j].
Easy
Dynamic Programming Fundamentals
dp[r][c] = dp[r−1][c] + dp[r][c−1]; one row suffices.
Medium
Dynamic Programming Fundamentals
dp[i] = max(dp[i−1], dp[i−2] + nums[i]).
Medium
Dynamic Programming Fundamentals
dp[a] = 1 + min(dp[a − c]); infinity if unreachable.
Medium
Dynamic Programming Fundamentals
dp[r][c] = grid[r][c] + min(top, left).
Medium
Dynamic Programming Fundamentals
Bottom-up: dp[j] = t[i][j] + min(dp[j], dp[j+1]).
Medium
1D Dynamic Programming
rob(i) = max(rob(i−1), rob(i−2) + nums[i]).
Medium
1D Dynamic Programming
Circular: max(rob(nums[1:]), rob(nums[:-1])).
Medium
1D Dynamic Programming
dp[i] += dp[i−1] if s[i−1] != '0'; dp[i] += dp[i−2] if 10 <= s[i−2..i−1] <= 26.
Medium
1D Dynamic Programming
dp[i] = any(dp[j] and s[j:i] in words) — limit j by the max word length.
Medium
1D Dynamic Programming
O(n^2): dp[i] = 1 + max(dp[j] for j < i with a[j] < a[i]). O(n log n): tails + bisect.
Medium
1D Dynamic Programming
Track max and min product ending here.
Medium
1D Dynamic Programming
States hold/sold/rest; sold today → rest tomorrow.
Medium
1D Dynamic Programming
cash = max(cash, hold + p − fee); hold = max(hold, cash − p).
Medium
1D Dynamic Programming
Bucket totals by value, then House Robber over values.
Medium
1D Dynamic Programming
Track (length, count) per index; equal lengths add counts.
Medium
1D Dynamic Programming
DP works in O(n^2); greedy BFS levels in O(n).
Medium
1D Dynamic Programming
Sort width ascending, height DESCENDING for equal widths; LIS on heights in O(n log n).
Hard
1D Dynamic Programming
buy[j], sell[j] for j transactions; if k >= n/2 it's unlimited.
Hard
1D Dynamic Programming
dp[day] = min(dp[day−1]+c1, dp[day−7]+c7, dp[day−30]+c30) on travel days; dp[day] = dp[day−1] otherwise.
Medium
2D DP — Grids & Strings
Grid ways with obstacles set to 0.
Medium
2D DP — Grids & Strings
dp[r][c] = grid[r][c] + min(top, left).
Medium
2D DP — Grids & Strings
dp[r][c] = 1 + min(top, left, top-left) when the cell is '1'.
Medium
2D DP — Grids & Strings
Match: dp[i−1][j−1] + 1; else max(dp[i−1][j], dp[i][j−1]).
Medium
2D DP — Grids & Strings
Expand around centers O(n^2) time, O(1) space; or pal[i][j] table.
Medium
2D DP — Grids & Strings
Count expansions around all 2n−1 centers.
Medium
2D DP — Grids & Strings
dp[i][j] over s[i..j]; equal ends → 2 + dp[i+1][j−1]; else max of dropping an end.
Medium
2D DP — Grids & Strings
dp[i][j] = s3[i+j−1] came from s1[i−1] (and dp[i−1][j]) or s2[j−1] (and dp[i][j−1]).
Medium
2D DP — Grids & Strings
Equal chars: diagonal; else 1 + min(insert, delete, replace).
Medium
2D DP — Grids & Strings
m + n − 2·LCS.
Medium
2D DP — Grids & Strings
Go backwards from the princess: need[r][c] = max(1, min(right, down) − dungeon[r][c]).
Hard
2D DP — Grids & Strings
dp[i][j] = dp[i−1][j] + (s[i−1] == t[j−1] ? dp[i−1][j−1] : 0).
Hard
2D DP — Grids & Strings
'*' → dp[i][j−1] (empty) or dp[i−1][j] (eat one char).
Hard
2D DP — Grids & Strings
'x*' → skip it (dp[i][j−2]) or, if x matches s[i−1], consume one char (dp[i−1][j]).
Hard
2D DP — Grids & Strings
Both robots move row by row: dp[row][c1][c2] with 9 transitions.
Hard
Knapsack & Subset DP
0/1 subset-sum to total/2; iterate capacity backwards (or use a bitset).
Medium
Knapsack & Subset DP
Count subsets with sum (total + target)/2; check parity and bounds.
Medium
Knapsack & Subset DP
Split into two groups as equal as possible: subset-sum closest to total/2.
Medium
Knapsack & Subset DP
2D-capacity 0/1 knapsack: dp[zeros][ones], both iterated backwards.
Medium
Knapsack & Subset DP
Unbounded knapsack minimizing count.
Medium
Knapsack & Subset DP
Count combinations: coins in the OUTER loop, amounts forwards.
Medium
Knapsack & Subset DP
Counts ordered sequences (permutations): amount in the OUTER loop.
Medium
Knapsack & Subset DP
Unbounded knapsack with items = squares <= n, minimizing count.
Medium
Knapsack & Subset DP
dp[members][profit capped at minProfit] counting schemes; 0/1 over crimes.
Hard
Knapsack & Subset DP
Group knapsack: each die is a group; pick exactly one face per group.
Medium
Knapsack & Subset DP
n <= 30 with huge values: meet in the middle — enumerate subset sums per half by size, binary search.
Hard
Advanced DP (Interval, Tree, Bitmask, Digit)
Each node returns (rob it, skip it); rob = val + skip(left) + skip(right).
Medium
Advanced DP (Interval, Tree, Bitmask, Digit)
Catalan: G(n) = sum over root i of G(i−1)·G(n−i).
Medium
Advanced DP (Interval, Tree, Bitmask, Digit)
Interval DP over split points (or a monotonic stack greedy).
Medium
Advanced DP (Interval, Tree, Bitmask, Digit)
dp[i][j] = best score difference for the player to move on piles i..j.
Medium
Advanced DP (Interval, Tree, Bitmask, Digit)
dp[i][j] = min over k of dp[i][k] + dp[k][j] + v[i]·v[k]·v[j].
Medium
Advanced DP (Interval, Tree, Bitmask, Digit)
Bitmask DP: dp[mask] = sum used modulo target; valid if a next item fits.
Medium
Advanced DP (Interval, Tree, Bitmask, Digit)
Choose the LAST balloon k in (i, j): dp[i][k] + dp[k][j] + a[i]·a[k]·a[j].
Hard
Advanced DP (Interval, Tree, Bitmask, Digit)
Sort cuts with ends added; interval DP over cut indices; cost = segment length.
Hard
Advanced DP (Interval, Tree, Bitmask, Digit)
dp[i][j]; if s[k] == s[i] the print of s[i] can extend to cover k.
Hard
Advanced DP (Interval, Tree, Bitmask, Digit)
BFS over (node, mask).
Hard
Advanced DP (Interval, Tree, Bitmask, Digit)
TSP over words with overlap costs: dp[mask][last].
Hard
Advanced DP (Interval, Tree, Bitmask, Digit)
Tree DP with 3 states per node.
Hard
Advanced DP (Interval, Tree, Bitmask, Digit)
Digit DP (or per-position counting formula).
Hard
Advanced DP (Interval, Tree, Bitmask, Digit)
Count shorter lengths directly, then walk N's digits with the tight flag.
Hard
Advanced DP (Interval, Tree, Bitmask, Digit)
Digit DP with (pos, used-digit mask, tight, started).
Hard
Advanced DP (Interval, Tree, Bitmask, Digit)
Rerooting: ans[child] = ans[parent] − size[child] + (n − size[child]).
Hard
Segment Trees, Fenwick Trees & Sparse Tables
Fenwick tree: point update with delta, query prefix(r) − prefix(l−1).
Medium
Segment Trees, Fenwick Trees & Sparse Tables
Coordinate compress; scan right to left; BIT counts how many smaller values were seen.
Hard
Segment Trees, Fenwick Trees & Sparse Tables
BIT over compressed values: count earlier elements > 2·x.
Hard
Segment Trees, Fenwick Trees & Sparse Tables
BIT over compressed prefix sums: count earlier P in [P − upper, P − lower].
Hard
Segment Trees, Fenwick Trees & Sparse Tables
2D Fenwick tree.
Medium
Segment Trees, Fenwick Trees & Sparse Tables
Sweep with a sorted map of +1/−1, or a dynamic segment tree with lazy range add + max.
Hard
Segment Trees, Fenwick Trees & Sparse Tables
Segment tree over compressed coordinates with range assign and range max.
Hard
Segment Trees, Fenwick Trees & Sparse Tables
dp[v] = 1 + max(dp over values in [v − k, v − 1]) with a max segment tree indexed by value.
Hard
Segment Trees, Fenwick Trees & Sparse Tables
Sorted interval map, or a segment tree with range assign.
Hard
Segment Trees, Fenwick Trees & Sparse Tables
BIT of counts: cost = min(count < x, count > x).
Hard
String Algorithms
KMP or Z on pattern + '#' + text.
Easy
String Algorithms
s is in (s+s)[1:-1]; or KMP: n % (n − lps[n−1]) == 0 and lps[n−1] > 0.
Easy
String Algorithms
The last value of the KMP prefix function.
Hard
String Algorithms
Longest palindromic prefix = lps of s + '#' + reverse(s); prepend the reversed rest.
Hard
String Algorithms
Rolling hash (or 2-bit encoding) of every 10-length window in a set.
Medium
String Algorithms
Binary search the length; check duplicates with a rolling hash.
Hard
String Algorithms
Manacher's algorithm gives O(n).
Medium
String Algorithms
Sum of the Z-function plus n.
Hard
String Algorithms
Rolling hash to compare halves in O(1); set of hashes of valid substrings.
Hard
String Algorithms
Z-function: first multiple of k where z[i] >= n − i.
Hard
Math & Number Theory
Reverse half the digits and compare; negatives and trailing zeros are not palindromes.
Easy
Math & Number Theory
Iterate the digit-square sum; detect a cycle with a set or Floyd.
Easy
Math & Number Theory
Propagate the carry from the end; prepend 1 if it survives.
Easy
Math & Number Theory
If s1+s2 == s2+s1 the answer is the prefix of length gcd(len1, len2).
Easy
Math & Number Theory
Sieve of Eratosthenes starting each crossing-out at p·p.
Medium
Math & Number Theory
Binary exponentiation; handle negative n.
Medium
Math & Number Theory
Grade-school multiplication: digit i·j goes to positions i+j and i+j+1.
Medium
Math & Number Theory
F(k) = F(k−1) + sum − n·a[n−k].
Medium
Math & Number Theory
C(m+n−2, m−1) — combinatorics instead of DP.
Medium
Math & Number Theory
For each anchor, hash the reduced slope (dy/g, dx/g) with normalized sign.
Hard
Math & Number Theory
a^(10x + d) = (a^x)^10 · a^d, processing digits with modular exponentiation.
Medium
Math & Number Theory
Multinomial coefficients per word using factorials and modular inverses.
Hard
Math & Number Theory
Try matrix exponentiation [[1,1],[1,0]]^n for O(log n).
Easy
Math & Number Theory
You lose iff n % 4 == 0 — find the pattern of losing positions.
Easy
Data Structure Design Problems
Array of buckets (lists of key/value pairs) with key % size hashing.
Easy
Data Structure Design Problems
After each push rotate the queue so the newest element is at the front.
Easy
Data Structure Design Problems
Pairs of (value, running min).
Medium
Data Structure Design Problems
Hash map + doubly linked list; move to front on access; evict tail.
Medium
Data Structure Design Problems
Array + map value → index; delete by swapping with the last element.
Medium
Data Structure Design Problems
Map key → list of (timestamp, value); binary search on get.
Medium
Data Structure Design Problems
Per-user tweet lists with a global timestamp; merge the followees' latest with a heap.
Medium
Data Structure Design Problems
Per index, list of (snap_id, value); binary search on get.
Medium
Data Structure Design Problems
check-in map by id; totals map keyed by (start, end) with (sum, count).
Medium
Data Structure Design Problems
Stack of iterators (or reversed lists); hasNext advances until an integer is on top.
Medium
Data Structure Design Problems
Queue of timestamps; pop those older than 300 seconds.
Medium
Data Structure Design Problems
key → (value, freq); freq → ordered set of keys (OrderedDict); track minFreq.
Hard
Data Structure Design Problems
Doubly linked list of count buckets, each holding a set of keys; map key → bucket.
Hard
Data Structure Design Problems
Trie of path components; nodes are dirs (children map) or files (content).
Hard