Start with one problem. Work out what each step needs, then choose what to store.
Problem
Given nums = [3, 2, 4, 7] and target = 6, return one pair of distinct original indices.
The result is [1, 2]: 2 + 4 == 6. Return [] when no pair exists.
Do not sort or reuse one position. Assume integer inputs.
Picture: Remember Earlier Partners
Look up the missing value, then return its saved earlier index
Reference drawing
Look up the missing value, then return its saved earlier index
Derivation
| index | num | needed | seen before query | Action |
|---|---|---|---|---|
| 0 | 3 | 3 | {} | Save 3: 0 |
| 1 | 2 | 4 | {3: 0} | Save 2: 1 |
| 2 | 4 | 2 | {3: 0, 2: 1} | Return [1, 2] |
The four things to remember
Cue
A missing partner suggests a lookup instead of scanning the array again.
State
Save one earlier index per value in seen. To count pairs, store frequencies instead.
Invariant
An invariant is a rule that stays true. Here, seen contains only values from earlier positions.
Move
Look up the partner first, then save the current value. This prevents using one position twice.
Code
The Two Sum solution:
def two_sum(nums: list[int], target: int) -> list[int]:
seen: dict[int, int] = {}
for index, num in enumerate(nums):
needed = target - num
if needed in seen:
return [seen[needed], index]
seen[num] = index
return []
Expected time is , with extra space.
Check [3], target 6: no earlier partner, so []. Check [3, 3]: the second query returns [0, 1].
Change 1: Count Every Index Pair
Count pairs of distinct indices. Store prior counts, not one index. Count matches before adding the current value.
def count_pairs(nums, target):
counts = {}
answer = 0
for value in nums:
answer += counts.get(target - value, 0)
counts[value] = counts.get(value, 0) + 1
return answer
Check. [3, 3, 3], target 6, adds 0, 1, then 2: total 3. [3] gives 0.
Change 2: Count Signed Zero-Sum Ranges
Count contiguous zero-sum ranges in [1, -1, 1].
A prefix sum is the total up to a boundary. Equal prefix sums mean the values between them sum to zero.
Count matching prefixes, including the initial zero.
def count_zero_ranges(nums):
counts = {0: 1}
prefix = answer = 0
for value in nums:
prefix += value
answer += counts.get(prefix, 0)
counts[prefix] = counts.get(prefix, 0) + 1
return answer
Check. [1, -1, 1] has two zero-sum ranges: [1, -1] and [-1, 1]. Empty input gives 0.
Failure: Remembering Only “Hash Map”
Knowing “hash map” is not enough. Explain what the map stores and why lookup comes before insertion.
Transfer Check
Why does a contiguous range not always imply a sliding window?
Reasoned Answer
Adding a negative value can lower the sum. A window that shrinks whenever the sum is too large may discard a valid answer. Prefix sums avoid that assumption.
A three-pass practice loop
First pass: learn one anchor per pattern
Start with the numbered problems. Use their related problems to practice a similar idea or compare a different method.
The snippets show the main steps, not complete solutions. Work out the missing setup before using them.
1. Subarray Sum Equals K
- Problem: Given an integer array and a target, count nonempty contiguous subarrays with that sum.
- A range sum is the difference between two prefix totals.
- Count earlier totals equal to
curr_sum - target; frequencies preserve multiple matching boundaries. - Seed one zero prefix. Count before storing, so only earlier boundaries contribute.
seen_sums = {0: 1}
curr_sum = count = 0
for n in nums:
curr_sum += n
count += seen_sums.get(curr_sum - target, 0)
seen_sums[curr_sum] = seen_sums.get(curr_sum, 0) + 1
Two Sum
-
Problem: Return two distinct indices in
numswhose values sum totarget, or[]if none exist. -
Change: Return one pair, not a range count. Keep one earlier index per value.
seen = {} # value -> earlier index -
Move: Query before storing.
[3, 3], target 6, returns[0, 1]without reusing an index.for i, n in enumerate(nums): if target - n in seen: return [seen[target - n], i] seen[n] = i
Random Pick with Weight
-
Problem: Given positive weights, choose an index randomly with probability proportional to its weight.
-
Contrast: Running totals mark weighted buckets instead of counting earlier matches.
prefix_sums = list(accumulate(weights)) -
Move: Draw an integer ticket and find its first enclosing boundary.
[1, 3]gives index 1 three tickets.ticket = random.randint(1, prefix_sums[-1]) return bisect_left(prefix_sums, ticket)
Product of Array Except Self
-
Problem: For each position in
nums, return the product of all other values without using division. -
Contrast: Combine contributions on either side of each index, without division. First store the product strictly to its left.
res, prefix = [1] * len(nums), 1 for i, n in enumerate(nums): res[i] = prefix prefix *= n -
Move: Multiply by the product strictly to the right.
[1, 2, 3, 4]produces[24, 12, 8, 6].suffix = 1 for i in range(len(nums) - 1, -1, -1): res[i] *= suffix suffix *= nums[i]
2. Minimum Window Substring
- Problem: Return the shortest substring of
scontaining every character int, including repeats, or""if none exists. - Cover every required character, including repeats; assume
tis nonempty. - Expand until the window covers
t, then shrink while coverage holds. - Removing a required occurrence creates a deficit. Keep the shortest valid window seen.
need, missing = Counter(t), len(t)
left = 0
for right, c in enumerate(s):
missing -= need[c] > 0
need[c] -= 1
while missing == 0:
# Save the shortest window [left, right].
need[s[left]] += 1
missing += need[s[left]] > 0
left += 1
Longest Substring Without Repeating Characters
-
Problem: Given a string, return the length of its longest substring without repeated characters.
-
Change: Keep characters unique instead of covering required characters. Store each character’s most recent position.
left = max_len = 0 char_map = {} -
Move: Jump past repeats inside the current window, never backward.
"abba"has maximum length 2.for right, c in enumerate(s): if c in char_map and char_map[c] >= left: left = char_map[c] + 1 char_map[c] = right max_len = max(max_len, right - left + 1)
3. 3Sum
- Problem: Find all unique triples in
numsthat sum to zero, using three distinct indices. - Sort, then fix one value and seek a pair that cancels it.
- A low total needs a larger left value; a high total needs a smaller right value.
- Skip repeated anchor and left values to avoid duplicate triples.
nums.sort()
res = []
for i, a in enumerate(nums):
if i > 0 and a == nums[i - 1]:
continue
l, r = i + 1, len(nums) - 1
while l < r:
total = a + nums[l] + nums[r]
if total == 0:
res.append([a, nums[l], nums[r]])
l += 1
while l < r and nums[l] == nums[l - 1]:
l += 1
elif total < 0:
l += 1
else:
r -= 1
Valid Palindrome II
-
Problem: Given a string, check whether deleting at most one character can make it a palindrome.
-
Contrast: Compare string ends instead of numeric totals. Allow at most one deletion.
l, r = 0, len(s) - 1 -
Move: At the first mismatch, skip either end and check the remainder.
"abca"succeeds;"abc"fails.while l < r: if s[l] != s[r]: skip_l, skip_r = s[l + 1:r + 1], s[l:r] return skip_l == skip_l[::-1] or skip_r == skip_r[::-1] l, r = l + 1, r - 1
4. Koko Eating Bananas
- Problem: Find the smallest integer speed, in bananas per hour, that finishes all piles within
hhours. Use one pile per hour. - Search speeds, not pile positions. If a speed finishes in time, every faster speed does too.
- Use ceiling division to count each pile’s hours.
- Keep a working speed, then try slower ones. Assume positive piles and enough hours for one visit per pile.
l, r = 1, max(piles)
ans = r
while l <= r:
mid = (l + r) // 2
hours = sum((p + mid - 1) // mid for p in piles)
if hours <= h:
ans, r = mid, mid - 1
else:
l = mid + 1
Binary Search
-
Problem: Given an ascending sorted array, return the index of
target, or-1if it is absent. -
Change: Find an exact value in a sorted array, rather than the smallest working speed.
l, r = 0, len(arr) - 1 -
Move: Discard
midafter a miss. In[1, 3, 5], target 3 is at index 1.while l <= r: mid = (l + r) // 2 if arr[mid] == target: return mid elif arr[mid] < target: l = mid + 1 else: r = mid - 1
5. Daily Temperatures
- Problem: For each day’s temperature, return the days until a warmer day; use zero if none follows.
- Store indices waiting for their first warmer day.
- Waiting temperatures stay the same or decrease from bottom to top. A warmer day resolves colder entries at the top.
- Pop the waiting index before subtracting it; days without a warmer day stay zero.
ans, stack = [0] * len(temperatures), []
for i, t in enumerate(temperatures):
while stack and t > temperatures[stack[-1]]:
waiting = stack.pop()
ans[waiting] = i - waiting
stack.append(i)
Valid Parentheses
-
Problem: Given only
(),[]and{}brackets, check whether each opener closes in the correct order. -
Contrast: Nested brackets close in reverse order; no temperature ordering is involved.
stack, mapping = [], {")": "(", "}": "{", "]": "["} -
Move: Match each closer with the latest opener, then require an empty stack.
"([)]"fails.for c in s: if c in mapping: if not stack or stack.pop() != mapping[c]: return False else: stack.append(c) return not stack
Basic Calculator II
-
Problem: Evaluate an expression of nonnegative integers using
+,-,*and/, without parentheses. Division truncates toward zero. -
Contrast: Parse a valid expression without parentheses. Store signed terms, but resolve multiplication and division immediately.
stack, num, sign = [], 0, "+" -
Move: A final operator flushes the last number.
"3+2*2"gives 7; division truncates toward zero.for c in s + "+": if c.isdigit(): num = num * 10 + int(c) elif c in "+-*/": if sign == "+": stack.append(num) elif sign == "-": stack.append(-num) elif sign == "*": stack.append(stack.pop() * num) elif sign == "/": stack.append(int(stack.pop() / num)) sign, num = c, 0
6. Merge Intervals
- Problem: Given intervals, merge overlapping ranges and return the nonoverlapping result; touching endpoints count as overlap.
- Sort by start time; only the last merged range can overlap the next interval.
- Extend that range’s end, or start a new range.
- Touching endpoints merge. This fragment assumes a nonempty interval list.
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for curr in intervals[1:]:
if curr[0] <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], curr[1])
else:
merged.append(curr)
Meeting Rooms II
-
Problem: Return the minimum rooms needed for meeting intervals. A room is free when its previous meeting ends.
-
Contrast: Count allocated rooms instead of merging ranges. Keep one ending time per room in a min-heap.
intervals.sort(key=lambda x: x[0]) min_heap = [] -
Move: Reuse the earliest-ending room when possible. The final heap size gives the required room count.
for start, end in intervals: if min_heap and min_heap[0] <= start: heapq.heappop(min_heap) heapq.heappush(min_heap, end)
7. Kth Largest Element
- Problem: Return the kth largest value in
nums, counting duplicates as separate entries. - Keep the largest
kvalues seen; the smallest retained value is the cutoff. - Push each value, then pop when the heap exceeds
kentries. - With
1 <= k <= len(nums), the final heap root is the answer. Duplicates count separately.
min_heap = []
for n in nums:
heapq.heappush(min_heap, n)
if len(min_heap) > k:
heapq.heappop(min_heap)
Merge k Sorted Lists
-
Problem: Given
ksorted linked lists, merge their nodes into one sorted linked list. -
Contrast: Keep one candidate head per sorted list, rather than the largest values. The source index breaks equal-value ties.
heap = [(node.val, i, node) for i, node in enumerate(lists) if node] heapq.heapify(heap) -
Move: Emit the smallest candidate, then advance only its source list.
[1, 4]and[2, 3]merge in order.while heap: _, i, node = heapq.heappop(heap) # Append node to the output before advancing its source. if node.next: heapq.heappush(heap, (node.next.val, i, node.next))
8. Jump Game
- Problem: Given maximum jump lengths in
nums, decide whether the last index is reachable from index 0. - Track the farthest position reachable from earlier reachable indices.
- An index beyond that bound cannot be reached; otherwise extend the bound with
i + n. - Reachability needs one bound, not a chosen jump path. Values are nonnegative.
furthest = 0
for i, n in enumerate(nums):
if i > furthest:
return False
furthest = max(furthest, i + n)
9. Reverse Linked List
- Problem: Given the head of a singly linked list, reverse its links and return the new head.
prevheads the reversed prefix;currheads the untouched suffix.- Save the next pointer before reversing the current link.
- Once
curris empty,previs the new head.
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev, curr = curr, nxt
Merge Two Sorted Lists
-
Problem: Merge two sorted singly linked lists into one sorted list by reusing their nodes.
-
Change: Reuse nodes in sorted order instead of reversing them. A dummy head anchors the output.
dummy = curr = ListNode(0) -
Move: Attach the smaller head and advance its source. Attach the remaining suffix when one source ends.
while l1 and l2: if l1.val < l2.val: curr.next, l1 = l1, l1.next else: curr.next, l2 = l2, l2.next curr = curr.next curr.next = l1 if l1 else l2
Linked List Cycle
-
Problem: Given a linked list, check whether following
nextlinks can revisit the same node. -
Contrast: Detect repeated node identity without changing links. Start a slow and a fast pointer together.
slow = fast = head -
Move: Advance one pointer twice as fast. Meeting means a cycle; reaching the end means no cycle.
while fast and fast.next: slow, fast = slow.next, fast.next.next if slow is fast: return True
10. LRU Cache
- Problem: Implement a cache with
getandput, evicting the least recently used key when capacity is exceeded. - A map finds each node; a doubly linked list orders keys from oldest to newest use.
- Each read or update moves its node to the newest end.
- On overflow, evict the oldest node from both structures. Dummy endpoints keep rewiring uniform.
# self.cache = {} (key -> node)
# self.head.next = self.tail; self.tail.prev = self.head
# self._remove(node); self._add_to_end(node)
# overflow: evict self.head.next from the list and map
11. Diameter of Binary Tree
- Problem: Given a binary tree, return its longest path length between any two nodes, measured in edges.
- Each child returns its depth. A path through this node uses both depths.
- Return one branch upward, but keep the best cross-node path separately.
- Measure diameter in edges: a one-node tree has diameter 0.
self.diameter = 0
def depth(node):
if not node:
return 0
l, r = depth(node.left), depth(node.right)
self.diameter = max(self.diameter, l + r)
return 1 + max(l, r)
Maximum Depth of Binary Tree
-
Problem: Return the number of nodes on the longest root-to-leaf path in a binary tree.
-
Change: Return only the longest downward path. Empty subtrees contribute zero.
if not root: return 0 -
Move: Add one node to the deeper child path. No separate diameter total is needed.
def maxDepth(root): return (1 + max(maxDepth(root.left), maxDepth(root.right)) if root else 0)
Binary Tree Level Order Traversal
-
Problem: Return a binary tree’s values level by level, from top to bottom and left to right.
-
Contrast: Group nodes by distance from the root. A queue represents one level at each outer iteration.
queue, res = deque([root] if root else []), [] -
Move: Process only the initial queue length. Newly queued children belong to the next level.
while queue: res.append([node.val for node in queue]) for _ in range(len(queue)): node = queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right)
Validate Binary Search Tree
-
Problem: Check BST ordering in a binary tree: every node’s left descendants must be smaller and right descendants larger.
-
Contrast: Pass allowed value bounds down to children instead of combining child depths.
low, high = -float("inf"), float("inf") -
Move: Tighten the upper bound on the left and lower bound on the right. Strict bounds reject duplicates.
def validate(node, low=-float("inf"), high=float("inf")): return (not node or low < node.val < high and validate(node.left, low, node.val) and validate(node.right, node.val, high))
12. Implement Trie
- Problem: Store lowercase words. Support insertion, whole-word lookup and checking whether any word starts with a given prefix.
- Lowercase words with a shared prefix reuse the same character path.
- A terminal marker distinguishes a complete word from a prefix.
- After inserting
"apple","app"is a prefix, not yet a stored word.
node = self.root
for c in word:
node = node.setdefault(c, {})
node["$"] = True
# search: follow existing edges and require "$" at the end
# startsWith: follow existing edges without the terminal test
13. Rotting Oranges
- Problem: In a grid, rot spreads to four-way neighbors each minute. Return minutes until all oranges rot, or
-1if impossible. - Start with all rotten cells;
freshcounts the remaining fresh oranges. - One queue layer is one minute. Mark neighbors when enqueuing them to prevent duplicate infection.
- Fresh cells left after the queue empties are unreachable.
queue, minutes = deque(rotten_cells), 0
while queue and fresh:
for _ in range(len(queue)):
r, c = queue.popleft()
for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 2
fresh -= 1
queue.append((nr, nc))
minutes += 1
Number of Islands
-
Problem: Given a grid of land and water, count islands connected horizontally or vertically, not diagonally.
-
Change: Count connected groups of land, not minutes. Each unvisited land cell starts one flood fill.
if grid[r][c] == "1": count += 1 dfs(r, c) -
Move: Mark before visiting the four neighbors. Diagonal land cells remain separate islands.
def dfs(r, c): if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == "1": grid[r][c] = "0" for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]: dfs(r + dr, c + dc)
Rotate Image
-
Problem: Rotate a square matrix 90 degrees clockwise in place, without using another matrix.
-
Contrast: Change cell positions, not connections. First transpose: swap entries across the main diagonal.
n = len(matrix) for r in range(n): for c in range(r + 1, n): matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c] -
Move: Reverse each transposed row.
[[1, 2], [3, 4]]becomes[[3, 1], [4, 2]]clockwise.for row in matrix: row.reverse()
14. Course Schedule
- Problem: Given courses and prerequisite pairs, decide whether all courses can be completed.
- Direct each edge from prerequisite to course.
- In-degree counts remaining prerequisites. A zero count means ready; finishing that course reduces its neighbors’ counts.
- If fewer than
numCoursescourses are processed, a cycle remains.
in_degree, adj = [0] * numCourses, defaultdict(list)
for c, p in prerequisites:
adj[p].append(c)
in_degree[c] += 1
queue = deque(i for i in range(numCourses) if in_degree[i] == 0)
# Pop ready courses and decrement each outgoing neighbor's in-degree.
# Enqueue a neighbor exactly when its in-degree reaches zero.
15. Redundant Connection
- Problem: Given a tree plus one undirected edge, return the last input edge whose removal restores a tree.
- Union-find tracks connected groups by their roots.
- An edge between equal roots closes a cycle; different roots can be joined.
- Use path compression and union by size when filling in the omitted setup.
def find(node):
if node != parent[node]:
parent[node] = find(parent[node])
return parent[node]
for u, v in edges:
ru, rv = find(u), find(v)
if ru == rv:
return [u, v]
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru
size[ru] += size[rv]
16. Network Delay Time
- Problem: Given directed edges with nonnegative travel times, return the time to reach all nodes from
k, or-1. - With nonnegative weights, expand the smallest known arrival time first.
- Update distances when a faster route is found. Skip older heap entries with worse times.
- The latest shortest arrival is the answer. Any unreachable node makes delivery impossible.
dist[k], heap = 0, [(0, k)]
while heap:
t, u = heapq.heappop(heap)
if t != dist[u]:
continue
for v, w in adj[u]:
if t + w < dist[v]:
dist[v] = t + w
heapq.heappush(heap, (dist[v], v))
17. Is Graph Bipartite?
- Problem: Can an undirected graph’s nodes form two groups such that every edge connects nodes from different groups?
- Connected nodes need different colors.
- A later visit must match a node’s existing color.
- Check every separate part of the graph. An odd cycle causes a color conflict.
color = {}
def is_bipartite(node, c):
if node in color:
return color[node] == c
color[node] = c
return all(is_bipartite(nei, 1 - c) for nei in adj[node])
return all(is_bipartite(node, 0) for node in range(len(adj)) if node not in color)
18. Coin Change
- Problem: Given positive coin values, find the fewest coins totaling
amount, with unlimited reuse. Return-1if impossible. - Use the remaining amount as the state. Try each positive coin that fits.
- Cache the fewest coins needed for each amount.
- Zero needs no coins. Infinity means no combination fits.
@lru_cache(None)
def dfs(rem):
if rem == 0:
return 0
return min((dfs(rem - c) + 1 for c in coins if c <= rem),
default=float("inf"))
House Robber
-
Problem: Given house values, return the most money you can take without taking from adjacent houses.
-
Contrast: Maximize money without taking adjacent houses. This array reminder assumes at least two houses.
dp = [0] * len(nums) dp[0], dp[1] = nums[0], max(nums[0], nums[1]) -
Move: Skip this house, or take it after the best total two houses back.
[2, 7, 9, 3, 1]gives 12.for i in range(2, len(nums)): dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
Word Break
-
Problem: Given a string and dictionary, decide whether the string can be split into dictionary words; words may be reused.
-
Change: Track which string prefixes can be made from dictionary words. Start with the empty prefix.
words = set(words) dp = [True] + [False] * len(s) -
Move: Extend any valid prefix with a dictionary word.
"cars"can use"ca"then"rs".for i in range(1, len(s) + 1): dp[i] = any(dp[j] and s[j:i] in words for j in range(i))
19. Edit Distance
- Problem: Return the fewest character insertions, deletions and replacements needed to turn one given string into another.
- Each cell aligns two prefixes and stores their minimum edit count.
- Matching characters use the diagonal unchanged; otherwise choose deletion, insertion or replacement.
- Empty-prefix borders cost the other prefix’s length.
dp[i][0], dp[0][j] = i, j
# dp[i][j] = dp[i-1][j-1] when w1[i-1] == w2[j-1]
# else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
# delete insert replace
20. Combination Sum
- Problem: Given distinct positive candidates, find all combinations that sum to
target. Each candidate may be used repeatedly. - Build all combinations of positive, distinct candidates that total the target.
- Choose a value, explore its remainder, then undo the choice.
- Reusing index
iallows repeated values; increasing indices avoid different orders of the same combination.
res = []
def backtrack(start, rem, path):
if rem == 0:
res.append(list(path))
return
for i in range(start, len(candidates)):
if candidates[i] > rem:
continue
path.append(candidates[i])
backtrack(i, rem - candidates[i], path)
path.pop()
Subsets
-
Problem: Given distinct integers, return every subset, including the empty subset.
-
Change: Every partial path is a valid answer, including the empty path. Remove the target-sum condition.
res = [] -
Move: Copy each path, then explore later indices only. Advancing to
i + 1prevents reusing the chosen position.def backtrack(start, path): res.append(list(path)) for i in range(start, len(nums)): path.append(nums[i]) backtrack(i + 1, path) path.pop()
Single Number
-
Problem: Given integers where every value appears twice except one, return the unpaired value.
-
Contrast: Every value appears twice except one. XOR cancels paired values without exploring possibilities.
ans = 0 -
Move: XOR all values together; order does not matter.
[2, 1, 2]leaves 1.for n in nums: ans ^= n
Second pass: study nearby variations
Open a related problem and note what changes. Explain why its steps work, then solve it without the snippet.
Mixed pass: choose the pattern yourself
Hide the pattern heading and ask:
- What does a simple solution do repeatedly?
- What data would avoid that repeated work?
- Why is each step correct, and what are the time and space costs?
Try first, then take a small hint if needed. Hide the hint and try again.
Practical screening problems
Practical coding screens wrap core data structures inside real service, log, parser, hierarchy, and ML tasks. Many reduce directly to the 20 anchors above; others rely on plain hash maps, queues, stacks, or string scans. Each card introduces the real-world setup, shows why obvious approaches break, and explains the algorithm in plain terms.
1. Stateful components and caches
P1. Sliding-Window Rate Limiter and Hit Counter
- Engineering context: Public APIs and LLM endpoints sit behind rate limiters so one runaway script cannot starve everyone else.
- Problem: Implement
allow(user_id, ts)permitting at mostlimitaccepted hits in(ts - window, ts], andget_hits(ts)for rolling counts. - Why naive fails: Resetting a counter each clock minute lets
limithits at12:00:59and12:01:00double the allowed rate. Saving every historical timestamp forever and scanning the whole list on each request also grows slower over time. - Solution: Map each
user_idin a hash map to adequeof accepted timestamps. Pop expired timestamps<= ts - windowfrom the left, checklen(q) < limit, then appendts. - Connection: Adapts
2. Minimum Window Substringto a live stream:appendmovesright, andpopleftmovesleft. For one high-QPS global hit counter, group hits into fixed-width(second, count)ring buckets.
class SlidingWindowRateLimiter:
def __init__(self, limit: int, window_sec: int):
self.limit, self.window_sec = limit, window_sec
self.hits = defaultdict(deque)
def allow(self, user_id: str, ts: int) -> bool:
q, cutoff = self.hits[user_id], ts - self.window_sec
while q and q[0] <= cutoff:
q.popleft()
if len(q) >= self.limit:
return False
q.append(ts)
return True
P2. Token Bucket Rate Limiter
- Engineering context: API gateways cap each user’s average request rate while still allowing short bursts when a page loads.
- Problem: Allow bursts up to
capacitytokens per user while refilling quota steadily atratetokens per second. - Why naive fails: Keeping a timestamp
dequelikeP1stores100,000entries per user when the hourly limit is100,000. Running a background timer every second to refill millions of idle users also wastes CPU. - Solution: Store only two numbers
(tokens, last_ts)per user in a hash map. On each request, lazily add(ts - last_ts) * ratecapped atcapacity, then subtract one token iftokens >= 1. - Connection: Outside the 20. Solves the same rate-limiting goal as
P1, replacing#2’s timestampdequewith per-user hash map state.
class TokenBucketLimiter:
def __init__(self, capacity: float, rate: float):
self.capacity, self.rate, self.state = capacity, rate, {}
def allow(self, user_id: str, ts: float) -> bool:
tokens, last_ts = self.state.get(user_id, (self.capacity, ts))
tokens = min(self.capacity, tokens + (ts - last_ts) * self.rate)
if tokens < 1.0:
self.state[user_id] = (tokens, ts)
return False
self.state[user_id] = (tokens - 1.0, ts)
return True
P3. Expiring Cache (TTL + LRU, plus LFU and Heap Cleanup)
- Engineering context: Online services cache recent database or ML feature lookups in limited RAM. Each cached entry becomes stale after
ttlseconds. - Problem: Support bounded
get(key, now)andput(key, val, ttl, now)that never return expired data and evict expired keys before LRU keys. - Why naive fails: Plain LRU ignores expiration, serving stale values or evicting hot keys while expired keys waste RAM. Scanning the entire cache on every call to purge expired entries turns reads into scans.
- Solution: Store
(val, expires_at)inside anOrderedDict(hash map plus doubly linked list). Delete expired keys lazily onget; when inserting a new key into a full cache, sweep expired keys beforepopitem(last=False). - Connection: Directly extends
10. LRU Cache(and9. Reverse Linked Listpointer rewiring whenOrderedDictis disallowed). At large capacity, add7. Kth Largest’s min-heap(expires_at, ver, key)for cleanup. ForLFU, map each frequency to its ownOrderedDict.
class TTLLRUCache:
def __init__(self, capacity: int):
self.capacity, self.store = capacity, OrderedDict()
def get(self, key: str, now: int):
if key not in self.store:
return None
val, exp = self.store[key]
if now >= exp:
del self.store[key]
return None
self.store.move_to_end(key)
return val
def put(self, key: str, val, ttl: int, now: int) -> None:
if self.capacity <= 0 or ttl <= 0:
self.store.pop(key, None)
return
if key not in self.store and len(self.store) >= self.capacity:
for k in [k for k, (_, exp) in self.store.items() if now >= exp]:
del self.store[k]
if len(self.store) >= self.capacity:
self.store.popitem(last=False)
self.store[key] = (val, now + ttl)
self.store.move_to_end(key)
P4. Point-in-Time Feature Store (TimeMap)
- Engineering context: ML training pipelines join past user clicks at
t = 30with user features as oft = 30. - Problem: Implement
set(key, val, ts)for increasing timestamps andget(key, ts)returning the latest value written at or beforets. - Why naive fails: Overwriting a normal dictionary (
store[key] = val) erases history, so yesterday’s click reads tomorrow’s feature value (future data leakage). Appending(ts, val)history and scanning the list from the start on everygettakes time per row. - Solution: Map each key in a hash map to parallel sorted
timesandvalslists. Run binary search (bisect_right(times, ts) - 1) to jump straight to the latest timestamp<= tsin time. - Connection: Adapts
4. Koko Eating Bananas. Both binary-search the exact split point where a monotonicTrue/Falsecondition (time <= ts) flips.
class TimeMap:
def __init__(self):
self.times, self.vals = defaultdict(list), defaultdict(list)
def set(self, key: str, val, ts: int) -> None:
self.times[key].append(ts)
self.vals[key].append(val)
def get(self, key: str, ts: int):
idx = bisect_right(self.times.get(key, ()), ts) - 1
return self.vals[key][idx] if idx >= 0 else None
P5. In-Memory Store with Nested Transactions
- Engineering context: Databases and config editors group edits inside
begin(), then save them withcommit()or undo them withrollback(). - Problem: Implement
get,set,delete, plus nestedbegin(),commit(), androllback(). - Why naive fails: Copying the full dictionary on every
begin()(backup = base.copy()) copies millions of untouched keys for a one-key edit. Storing only changed keys breaks ondelete(k): removingkfrom the top dict makesget(k)readbase[k]. - Solution: Push an empty hash map delta onto a stack on
begin(). Search overlays top-down ongetbeforebase. Record deletes with a unique_DELETEDmarker, keeping it across inner commits. - Connection: Outside the 20. Uses a plain LIFO stack of hash maps, unlike
5. Daily Temperatureswhich maintains monotonic stack order.
_DELETED = object()
class TransactionalKV:
def __init__(self):
self.base, self.stack = {}, []
def get(self, key: str):
for layer in reversed(self.stack):
if key in layer:
return None if layer[key] is _DELETED else layer[key]
return self.base.get(key)
def set(self, key: str, val) -> None:
(self.stack[-1] if self.stack else self.base)[key] = val
def delete(self, key: str) -> None:
if self.stack:
self.stack[-1][key] = _DELETED
else:
self.base.pop(key, None)
def begin(self) -> None:
self.stack.append({})
def rollback(self) -> bool:
return bool(self.stack) and (self.stack.pop() is not None)
def commit(self) -> bool:
if not self.stack:
return False
top = self.stack.pop()
if self.stack:
self.stack[-1].update(top)
else:
for k, v in top.items():
self.base.pop(k, None) if v is _DELETED else self.base.__setitem__(k, v)
return True
P6. Streaming Moving Average, Log Deduplicator, and Funnel Counter
- Engineering context: Live monitoring pipelines smooth noisy sensor readings, silence duplicate error spam, and count users completing
visit -> cart -> checkout. - Problem: Compute a last-
Wmoving average, suppress repeated messages withincooldown, and count users completing orderedsteps. - Why naive fails: Calling
sum(readings[-W:])on every event re-adds allWnumbers each time instead of updating in . Saving every log line or full click history in RAM just to check cooldowns or funnels wastes gigabytes. - Solution: Maintain a fixed-capacity
dequeplus running total forMovingAveragein . Store one scalar per key in a hash map for log cooldowns (last_ts[msg]) and funnels (progress[user] = next_step_idx). - Connection: Outside the 20.
MovingAverageshares#2’sdequeboundary updates without frequency maps. Log dedup and funnels keep one value per key in a hash map.
class MovingAverage:
def __init__(self, size: int):
self.size, self.q, self.total = size, deque(), 0.0
def next(self, val: float) -> float:
self.q.append(val)
self.total += val
if len(self.q) > self.size:
self.total -= self.q.popleft()
return self.total / len(self.q)
def count_completed_funnels(events: list, steps: list) -> int:
progress, done = defaultdict(int), 0
for user, ev in events:
idx = progress[user]
if idx < len(steps) and ev == steps[idx]:
progress[user] = idx + 1
done += idx + 1 == len(steps)
return done
2. Logs, event streams, and time-series
P7. Rolling Top-K Active Users or Failing Endpoints
- Engineering context: On-call dashboards show which users or failing URLs spiked over the last five minutes during live incidents.
- Problem: Record
(ts, key)events and return thekmost frequent keys inside(now - window, now]. - Why naive fails: Keeping one all-time counter per endpoint never forgets yesterday’s resolved outage, hiding smaller new spikes. Filtering and re-counting raw log events from scratch on every dashboard refresh is per query.
- Solution: Append arriving events to a
dequeand increment a hash mapCounter. Pop expired events from the left and delete zero-count keys. At query time, push(count, key)through a min-heap of sizekin . - Connection: Combines
2. Minimum Window Substring(slidingdequeplus live frequency map) with7. Kth Largest Element(bounded min-heap).
class RollingTopK:
def __init__(self, window_sec: int):
self.window_sec, self.events, self.counts = window_sec, deque(), Counter()
def _evict(self, now: int) -> None:
while self.events and self.events[0][0] <= now - self.window_sec:
_, key = self.events.popleft()
self.counts[key] -= 1
if self.counts[key] == 0:
del self.counts[key]
def record(self, ts: int, key: str) -> None:
self.events.append((ts, key))
self.counts[key] += 1
self._evict(ts)
def top_k(self, k: int, now: int) -> list:
self._evict(now)
heap = []
for key, cnt in self.counts.items():
heapq.heappush(heap, (cnt, key))
if len(heap) > k:
heapq.heappop(heap)
return [(key, cnt) for cnt, key in sorted(heap, reverse=True)]
P8. Burst Detection on Unordered, Duplicate Logs
- Engineering context: Distributed servers retry failed network sends, so collected log files often contain duplicate events and out-of-order timestamps.
- Problem: Given unsorted
(event_id, user_id, ts)logs with duplicates, return users having at leastmunique events withinwindowseconds. - Why naive fails: Feeding raw logs straight into
P1’s livedequecounts retriedevent_ids twice, falsely flagging normal users. Worse, one out-of-orderts = 100arriving beforets = 55causesP1to evict50before[50, 52, 55]is ever checked. - Solution: Filter duplicate
event_ids with a hash set and sort unique events byts. Then slide a per-userdequewindow, dropping timestamps<= ts - window. - Connection: Uses sorting (
#6setup) to restore chronological order, then applies2. Minimum Window Substring’s sliding window per user.
def flag_bursty_users(logs: list, min_events: int, window_sec: int) -> set:
seen, unique = set(), []
for eid, uid, ts in logs:
if eid not in seen:
seen.add(eid)
unique.append((ts, uid))
unique.sort()
windows, flagged = defaultdict(deque), set()
for ts, uid in unique:
q = windows[uid]
q.append(ts)
while q and q[0] <= ts - window_sec:
q.popleft()
if len(q) >= min_events:
flagged.add(uid)
return flagged
P9. Total Active Session Time and Peak Concurrent Load
- Engineering context: Cloud billing charges for total active wall-clock time, whereas capacity planning provisions enough machines for the busiest instant.
- Problem: Given half-open
[start, end)intervals, return both total covered duration and maximum simultaneous sessions. - Why naive fails: Simply summing
(end - start)double-counts overlapping sessions ([1, 5)and[2, 6)give8instead of5). Marking every second in an array (for t in range(start, end)) times out when Unix timestamps span millions of seconds. - Solution: For covered duration, sort intervals by
start, merge overlaps, and sumend - start. For peak concurrency, emit(start, +1)and(end, -1)events and sort them (-1before+1on ties). Track the maximum running total in one pass. - Connection: Covered duration is
6. Merge Intervals. Peak concurrency sorts interval boundaries (#6) and equals the room count fromMeeting Rooms II(#6/#7).
def total_active_time(intervals: list) -> int:
if not intervals:
return 0
s_iv = sorted(intervals)
cs, ce, total = s_iv[0][0], s_iv[0][1], 0
for s, e in s_iv[1:]:
if s <= ce:
ce = max(ce, e)
else:
total += ce - cs
cs, ce = s, e
return total + (ce - cs)
def peak_concurrency(intervals: list) -> int:
events = sorted([(s, 1) for s, _ in intervals] + [(e, -1) for _, e in intervals])
active = peak = 0
for _, delta in events:
active += delta
peak = max(peak, active)
return peak
P10. Signed Net-Change Windows and Best F1 Threshold Sweep
- Engineering context: Audits check periods where credits and debits net to
k. ML teams also pick a score cutoff maximizing F1. - Problem: Find the longest contiguous slice summing to
kon signed deltas. Also find the cutoff maximizing F1 on(score, label)pairs. - Why naive fails: Two-pointer windows fail on signed deltas because negative values lower sums, making
leftskip valid slices. For F1, testing every score cutoff by rescanning allnpredictions to recount TP and FP takes steps. - Solution: For signed slices, store each running prefix sum’s earliest index in a hash map and check
curr - k. For F1, sort descending byscoreand accumulate runningtpandfpcounts, grouping equal scores before computing F1. - Connection: Signed target windows directly adapt
1. Subarray Sum Equals K(storing earliest index instead of frequency). The F1 sweep reuses#1’s running prefix sums after sorting, without#1’s hash map.
def longest_target_window(deltas: list, k: int) -> int:
first_seen, curr, best = {0: -1}, 0, 0
for i, x in enumerate(deltas):
curr += x
if curr - k in first_seen:
best = max(best, i - first_seen[curr - k])
first_seen.setdefault(curr, i)
return best
def best_f1_threshold(preds: list) -> tuple:
pos = sum(y for _, y in preds)
if not pos or not preds:
return 0.0, 0.0
ordered = sorted(preds, key=lambda x: x[0], reverse=True)
tp = fp = i = 0
best_t, best_f1 = ordered[0][0], -1.0
while i < len(ordered):
t = ordered[i][0]
while i < len(ordered) and ordered[i][0] == t:
tp += ordered[i][1] == 1
fp += ordered[i][1] == 0
i += 1
f1 = (2.0 * tp) / (2 * tp + fp + (pos - tp))
if f1 > best_f1:
best_t, best_f1 = t, f1
return best_t, best_f1
P11. Latency Spike Lookahead and Online Calm Streak
- Engineering context: Monitors check how soon server latency worsens, or how many straight minutes stayed
<=the latest reading. - Problem: Stream latency readings via
next(val)and return consecutive latest readings<= val(and compute next-worse-spike wait times offline). - Why naive fails: Walking backward through past readings until a higher spike appears re-scans quiet minutes on every call. On a steadily rising latency curve,
ncalls take total comparisons. - Solution: Keep a monotonic strictly decreasing stack of
(latency, span). Pop entries<= valwhile adding theirspans into the new streak, then push(val, streak)in amortized time. - Connection: Offline lookahead is
5. Daily Temperatures;CalmStreakTrackerruns#5’s monotonic stack backward with absorbed span counts.
class CalmStreakTracker:
def __init__(self):
self.stack = [] # [(latency, span)], strictly decreasing
def next(self, val: float) -> int:
span = 1
while self.stack and self.stack[-1][0] <= val:
span += self.stack.pop()[1]
self.stack.append((val, span))
return span
3. Parsing, normalization, and rule evaluation
P12. Unix Path Resolution and cd Simulator
- Engineering context: Shells and file APIs combine
cwdand acdtarget into one clean path before checking permissions. - Problem: Given
cwdandtarget, return the canonical path handling leading/,.,.., and repeated slashes. - Why naive fails: Gluing
cwd + "/" + targetor running.replace("..", "")breaks on chained../../jumps and repeated//slashes. It also misses that atargetstarting with/ignorescwd, and..at/stays at/. - Solution: Initialize a list stack from
cwdunlesstargetstarts with/. Splittargeton/, skip empty or.tokens, pop on..if nonempty, and push directory names. - Connection: Outside the 20; matches
Valid Parentheses(plain LIFO stack, not#5’s monotonic stack). Supporting symlink maps adds14. Course Schedule’s visited-set cycle check.
def change_directory(cwd: str, target: str) -> str:
stack = [] if target.startswith("/") else [p for p in cwd.split("/") if p and p != "."]
for part in target.split("/"):
if not part or part == ".":
continue
if part == "..":
if stack:
stack.pop()
else:
stack.append(part)
return "/" + "/".join(stack)
P13. Parenthesized Expression and Boolean Rule Evaluator
- Engineering context: Feature flags, billing formulas, and alert filters evaluate user-written math or boolean rules safely without calling
eval(). - Problem: Evaluate an integer expression containing
+,-,*,/, and nested(...), truncating division toward zero. - Why naive fails: Left-to-right math turns
3 + 2 * 5into25instead of13because*precedes+. Nested parentheses also pause the outer calculation until the inner(...)finishes. - Solution: Scan with a term stack, current
num, and previous operatorop. Push+numor-numfor addition/subtraction, combine immediately withstack.pop()for*or/, and recurse on(. - Connection: Outside the 20; extends
Basic Calculator II(the stack contrast under#5) with recursion for parentheses. Boolean evaluators apply the exact same structure withORandAND.
def evaluate_math(expr: str) -> int:
def parse(i: int) -> tuple:
stack, num, op = [], 0, "+"
while i < len(expr):
ch = expr[i]
if ch.isdigit():
num = num * 10 + int(ch)
elif ch == "(":
num, i = parse(i + 1)
if (not ch.isdigit() and ch not in (" ", "(")) or i == len(expr) - 1 or ch == ")":
if op == "+":
stack.append(num)
elif op == "-":
stack.append(-num)
elif op == "*":
stack.append(stack.pop() * num)
elif op == "/":
stack.append(int(stack.pop() / num))
if ch == ")":
return sum(stack), i
op, num = ch, 0
i += 1
return sum(stack), i
return parse(0)[0]
P14. Quoted CSV Parser and Version or Custom-Order Sorting
- Engineering context: Data pipelines import CSV rows like
"San Jose, CA",42, and deploy tools order release versions like1.2and1.10. - Problem: Parse one CSV row with
"..."quotes,""escapes, and empty columns. Also sort dotted versions or words under a custom alphabet. - Why naive fails: Calling
line.split(",")cuts"San Jose, CA"in half because it ignores quotation marks. Plain string sorting compares character by character, so it puts"1.10"before"1.2"because'1' < '2'. - Solution: Scan characters with an
in_quotesboolean state, splitting on,only outside quotes and advancingi += 2on"". For sorting, map each version or word into an integer tuple sort key. - Connection: Outside the 20. Relies on a single-pointer state machine and tuple sort keys rather than
#3’s two pointers or#6’s interval merge.
def parse_csv_line(line: str) -> list:
fields, cur, in_quotes, i = [], [], False, 0
while i < len(line):
ch = line[i]
if in_quotes:
if ch == '"' and i + 1 < len(line) and line[i + 1] == '"':
cur.append('"')
i += 2
continue
elif ch == '"':
in_quotes = False
else:
cur.append(ch)
elif ch == '"':
in_quotes = True
elif ch == ",":
fields.append("".join(cur))
cur = []
else:
cur.append(ch)
i += 1
if in_quotes:
raise ValueError("Unclosed quote")
return fields + ["".join(cur)]
def version_key(v: str) -> tuple:
parts = [int(p) for p in v.split(".")]
while len(parts) > 1 and parts[-1] == 0:
parts.pop()
return tuple(parts)
4. Hierarchies, dependencies, and entity merging
P15. In-Memory File System (mkdir, ls, write_file, read_file)
- Engineering context: Cloud notebooks, browser IDEs, and unit tests simulate folders and files in RAM without touching disk.
- Problem: Implement
mkdir,write_file,read_file, and sortedlsfor/paths. - Why naive fails: One flat dict of full paths like
{"/a/b/c.txt": "hi"}forcesls("/a")to scan every file checkingstartswith("/a/"). It also needs awkward workarounds to represent empty folders created bymkdir. - Solution: Represent folders and files as a Trie of
_FSNodeobjects keyed by path segment (childrenhash map,is_file,content). Reuse one_walk(path, create)helper across methods. - Connection: Directly adapts
12. Implement Trie, branching on path names ("src") instead of characters.
class _FSNode:
def __init__(self, is_file: bool = False, content: str = ""):
self.is_file, self.content, self.children = is_file, content, {}
class InMemoryFS:
def __init__(self):
self.root = _FSNode()
def _walk(self, path: str, create: bool = False) -> _FSNode:
node = self.root
for part in [p for p in path.split("/") if p]:
if part not in node.children:
if not create:
raise FileNotFoundError(path)
node.children[part] = _FSNode()
node = node.children[part]
return node
def mkdir(self, path: str) -> None:
self._walk(path, create=True)
def write_file(self, path: str, content: str) -> None:
parts = [p for p in path.split("/") if p]
parent = self._walk("/" + "/".join(parts[:-1]), create=True)
parent.children[parts[-1]] = _FSNode(True, content)
def read_file(self, path: str) -> str:
return self._walk(path).content
def ls(self, path: str) -> list:
node = self._walk(path)
return [[p for p in path.split("/") if p][-1]] if node.is_file else sorted(node.children)
P16. Org Chart Common Manager, Subtree Cost, and Inherited Permissions
- Engineering context: HR and access-control services represent company reporting lines as a tree where each manager lists direct reports.
- Problem: Find the lowest common manager of
aandb(Noneif missing). Also sum subtree cost and compute inherited permissions. - Why naive fails: Without
.managerpointers, testing every manager top-down by re-searching its subtree repeats work in time. Returning a node when just one target name matches also gives a wrong answer if the second employee is missing. - Solution: Run bottom-up post-order DFS returning
(found_count, lca)acrossnode.reports(and summing costs upward). For inherited permissions, run top-down pre-order DFS passinginherited | set(node.perms)to children. - Connection: Common manager and cost rollup adapt
11. Diameter of Binary Treeto N-ary trees. Inherited permissions contrast top-down passing (Validate Binary Search Treeunder#11).
def nearest_common_manager(root, a: str, b: str):
def dfs(node):
if node is None:
return 0, None
found = int(node.name in (a, b))
for child in node.reports:
c_found, lca = dfs(child)
if lca is not None:
return 2, lca
found += c_found
return (2, node) if found == 2 else (found, None)
return dfs(root)[1]
def effective_permissions(root) -> dict:
out = {}
def walk(node, inherited: set) -> None:
if node is not None:
mine = inherited | set(node.perms)
out[node.name] = mine
for child in node.reports:
walk(child, mine)
walk(root, set())
return out
P17. Parallel Pipeline Waves and Template Variable Resolver
- Engineering context: ML workflow engines run independent pipeline steps in parallel batches, and config loaders expand
${var}placeholders likeckpt = "${root}/ckpt". - Problem: Partition
(task, prereq)dependencies into parallel waves (raising on cycles), and expand{key: "...${other}..."}templates catching cycles while allowing shared keys. - Why naive fails: Rescanning all tasks each round for unblocked work takes passes and hangs on circular dependencies. For
${var}, one-pass replacement fails on out-of-order keys, and a plainvisitedset mistakes shared variables for cycles. - Solution: For waves, run Kahn’s topological sort (
in_degreemap plus BFSdeque) popping onelen(ready)batch per wave. For${var}templates, run 3-state memoized DFS (0=unseen, 1=visiting, 2=done), raising onvisitingand cachingdone. - Connection: Both directly adapt
14. Course Schedule(schedule_wavesadds13. Rotting Oranges’s level loop to Kahn’s BFS;resolve_templatesadds memoization to#14’s cycle DFS).
def schedule_waves(tasks: list, deps: list) -> list:
adj, deg = defaultdict(list), {t: 0 for t in tasks}
for task, pre in deps:
adj[pre].append(task)
deg[task] += 1
ready, waves, done = deque(t for t in tasks if deg[t] == 0), [], 0
while ready:
wave = [ready.popleft() for _ in range(len(ready))]
done += len(wave)
for u in wave:
for v in adj[u]:
deg[v] -= 1
if deg[v] == 0:
ready.append(v)
waves.append(wave)
if done != len(tasks):
raise ValueError("Cycle detected")
return waves
P18. Account and Contact Deduplication
- Engineering context: Sign-up and fraud tools merge duplicate user profiles whenever they share an email or phone number.
- Problem: Merge
[name, email_1, email_2, ...]records belonging to the same person into sorted email lists. - Why naive fails: Comparing every pair of records takes time and still misses indirect chains. Record 1
(a, b)and Record 3(c, d)share nothing directly, yet Record 2(b, c)links them. - Solution: Link each account’s emails to its first email in an undirected adjacency map. Run DFS or BFS with a
visitedset to collect each connected component (use Union-Find for streaming merges). - Connection: Directly adapts
15. Redundant Connection(connected components via Union-Find online, or graph DFS in batch).
def merge_accounts(accounts: list) -> list:
adj, owner = defaultdict(set), {}
for acc in accounts:
for email in acc[1:]:
owner[email] = acc[0]
adj[acc[1]].add(email)
adj[email].add(acc[1])
seen, out = set(), []
for email in owner:
if email not in seen:
seen.add(email)
stack, comp = [email], []
while stack:
cur = stack.pop()
comp.append(cur)
for nei in adj[cur]:
if nei not in seen:
seen.add(nei)
stack.append(nei)
out.append([owner[email]] + sorted(comp))
return out
5. Scheduling, routing, and ML retrieval
P19. Minimum Workers, Cooldown Scheduler, and Live Leaderboard
- Engineering context: Backend schedulers size GPU pools for overlapping jobs, space out rate-limited task types, and rank live player scores.
- Problem: Schedule
["A", "A", "B", ...]withcooldownticks (Nonewhen idle). Also supportadd_scoreandtop(k)on a leaderboard. - Why naive fails: Checking every worker linearly per job takes time. Running rare tasks first strands frequent
"A"tasks in idle waits, and sorting all players ontop(k)costs . - Solution: For minimum workers, sort by start and track earliest finish in a min-heap (
Meeting Rooms IIunder#6). For cooldowns, pair a max-heap of counts with a(ready_tick, neg_cnt, task)deque. For leaderboards, pair a score hash map with a size-kmin-heap. - Connection: All three build directly on
7. Kth Largest Element’s heap frontier.
def schedule_with_cooldown(tasks: list, cooldown: int) -> list:
heap = [(-c, t) for t, c in Counter(tasks).items()]
heapq.heapify(heap)
cooling, out, tick = deque(), [], 0
while heap or cooling:
if cooling and cooling[0][0] <= tick:
_, nc, t = cooling.popleft()
heapq.heappush(heap, (nc, t))
if heap:
nc, t = heapq.heappop(heap)
out.append(t)
if nc + 1 < 0:
cooling.append((tick + cooldown + 1, nc + 1, t))
else:
out.append(None)
tick += 1
return out
P20. Inference Micro-Batcher and Weighted Load Balancer
- Engineering context: GPUs process prompt batches far faster than single prompts. Load balancers also split traffic unevenly (
90%prod,10%canary). - Problem: Flush queued requests when
len == max_batchor oldest wait>= max_wait_ms. Also route requests to backendiproportional to float weightw_i. - Why naive fails: Waiting strictly for
16prompts stalls night users forever, whereas batch size1wastes GPU throughput. Repeating server IDs in a list fails on float weights (0.13), and scanning weights per call costs . - Solution: Buffer requests in a FIFO
dequeand pop up tomax_batchitems whenever size ornow - q[0].arrival_mstriggers. For weighted routing, build cumulative prefix sums once and binary-searchrandom() * totalviabisect_rightin . - Connection: Micro-batching is outside the 20 (plain FIFO
deque, flushing rather than expiring like#2). Weighted routing combines1. Subarray Sum’s prefix sums (Random Pick with Weight) with4. Koko’s binary search on float weights.
class WeightedLoadBalancer:
def __init__(self, weights: list):
self.prefix, total = [], 0.0
for w in weights:
total += w
self.prefix.append(total)
self.total = total
def pick_backend(self) -> int:
return bisect_right(self.prefix, random.random() * self.total)
P21. Nearest Cache Server Distances and Obstacle Grid Routing
- Engineering context: Delivery networks and warehouse robots route each grid cell around walls to its closest healthy depot.
- Problem: Given
0servers,-1walls, and open client cells, compute shortest hop distance from every cell to any server. - Why naive fails: Straight-line
(row, col)formulas ignore walls that force detours. Running a separate breadth-first search starting from every client cell walks the whole grid over and over in time. - Solution: Enqueue all
0servers into one BFSdequeat distance0. Expand four-way neighbors layer by layer, settingdist[nr][nc] = dist[r][c] + 1on first visit. - Connection: Directly adapts
13. Rotting Oranges(multi-source BFS). Enqueue onlystartfor point-to-point routing; swapdequefor16. Network Delay Time’s min-heap on weighted edges.
def nearest_cache_distances(grid: list) -> list:
rows, cols, INF = len(grid), len(grid[0]), 10**9
dist = [[-1 if grid[r][c] == -1 else INF for c in range(cols)] for r in range(rows)]
q = deque((r, c) for r in range(rows) for c in range(cols) if grid[r][c] == 0)
for r, c in q:
dist[r][c] = 0
while q:
r, c = q.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == INF:
dist[nr][nc] = dist[r][c] + 1
q.append((nr, nc))
return dist
P22. Sparse Dot Product, Inverted-Index Top-K, and Feed Diversity
- Engineering context: Search and feed rankers score sparse million-feature vectors (~30 nonzero entries) and space out repeated creators in feeds.
- Problem: Multiply sorted
(dim, val)vectors, retrieve top-ksparse documents, and cap anyWconsecutive items tocapper creator. - Why naive fails: Dense million-float arrays waste RAM multiplying zeros, and scoring zero-overlap documents wastes 99% of CPU. Dropping repeat creators outright throws away good posts instead of saving them for a few slots later.
- Solution: Advance two pointers
i, jacross sorted non-zeros in . For retrieval, sumdim -> [(doc, w)]postings in a hash map and keep topkin a min-heap. For diversity, track the lastW - 1creators in adequeplusCounterwhile rotating blocked items inpending. - Connection:
sparse_dotadapts3. 3Sum’s sorted two pointers across two lists. Sparse retrieval uses a hash map plus7. Kth Largest, and diversity uses2. Minimum Window’sCounter.
def sparse_dot(a: list, b: list) -> float:
i = j = 0
total = 0.0
while i < len(a) and j < len(b):
if a[i][0] == b[j][0]:
total += a[i][1] * b[j][1]
i, j = i + 1, j + 1
elif a[i][0] < b[j][0]:
i += 1
else:
j += 1
return total
6. Multi-part build, verify, and extend
P23. Three-Stage Search Index (Postings, Pagination, Prefix Wildcard)
- Engineering context: Multi-part screens grow one service (a search index, bank ledger, or notification router) across 2 to 4 prompts.
- Problem: Index documents, then run multi-word
ANDsearch ranked by frequency (smallerdoc_idbreaks ties) with(offset, limit)and"prefix*"wildcards. - Why naive fails: Scanning raw document strings passes Stage 1, then crawls in Stage 2 when intersecting
"pytorch"with"the". Stuffing tokenization, scoring, and wildcards into one giant function also forces a bug-prone rewrite in Stage 3. - Solution: Isolate
_tokenize()first and storeword -> {doc_id: freq}in a hash map. Intersect from the shortest posting map, rank with a size-(offset + limit)min-heap, and expandprefix*via a vocabulary Trie. - Connection: Composes a plain hash map (Stage 1),
7. Kth Largest Element’s bounded heap (Stage 2), and12. Implement Trie(Stage 3).
class SearchIndex:
def __init__(self):
self.postings, self.trie = defaultdict(dict), {}
def add_doc(self, doc_id: int, text: str) -> None:
for w, freq in Counter(text.lower().split()).items():
if w not in self.postings:
node = self.trie
for ch in w:
node = node.setdefault(ch, {})
node[None] = w
self.postings[w][doc_id] = freq
def _expand(self, prefix: str) -> list:
node = self.trie
for ch in prefix:
if ch not in node:
return []
node = node[ch]
out, stack = [], [node]
while stack:
for k, v in stack.pop().items():
out.append(v) if k is None else stack.append(v)
return out
def _scores(self, tok: str) -> dict:
if not tok.endswith("*"):
return self.postings.get(tok, {})
merged = defaultdict(int)
for w in self._expand(tok[:-1]):
for doc_id, freq in self.postings[w].items():
merged[doc_id] += freq
return merged
def search(self, query: str, limit: int = 10, offset: int = 0) -> list:
maps = sorted((self._scores(t) for t in query.lower().split()), key=len)
if not maps or limit <= 0:
return []
common = set(maps[0]).intersection(*maps[1:])
heap = []
for doc_id in common:
heapq.heappush(heap, (sum(m[doc_id] for m in maps), -doc_id))
if len(heap) > offset + limit:
heapq.heappop(heap)
ranked = [-neg_id for _, neg_id in sorted(heap, reverse=True)]
return ranked[offset : offset + limit]
Review schedule
Try the problem again after 1, 3, 7 and 14 days. Adjust the gaps if it is too easy or difficult. Record what went wrong:
- Choosing the method.
- What to store.
- Why the step works.
- Writing the code.
- Edge cases.
- Time and space costs.
Quick pattern map
| Prompt clue | What to track | Method |
|---|---|---|
| Pair/duplicate | Prior values/counts | Map/set |
| Contiguous range | Boundaries/prefixes | Window/prefix |
| Sorted values | Ends/answer bounds | Pointers/bisection |
| Nested input | Unfinished items | Stack |
| Next greater | Waiting indices | Monotonic stack |
| Fewest unweighted steps | Layers | BFS |
| Nonnegative weighted path | Cheapest frontier | Dijkstra |
| Reachability | Visited frontier | Graph search |
| Every valid choice | Path/options | Backtracking |
| Repeated subproblem | Complete cached state | Dynamic programming |
| Time ranges | Active end | Intervals/greedy |
| Prerequisites | Incoming counts | Topological sort |
| Joining groups | Roots | Union-find |
| Node reordering | Saved next | Linked list |
| Shared prefixes | Prefix path | Trie |
Practical prompt map
| Practical prompt clue | Data structure and algorithm | Connection to the 20 |
|---|---|---|
Rate limit or hits in last W sec | Per-key deque of timestamps; or (tokens, last_ts) hash map | #2 sliding window; Token Bucket is plain dict |
| Bounded cache with TTL or LFU | OrderedDict + expiry sweep; min-heap for large TTL cleanup | Extends #10 LRU (#9 links, #7 heap) |
Latest feature value at <= ts | Hash map of sorted (times, vals) + bisect_right | #4 binary search on monotonic boundary |
| Weighted load balancer / sampler | Prefix-sum array + bisect_right on random target | #1 prefix totals + #4 binary search |
Nested begin / commit / rollback | Stack of overlay dicts + _DELETED tombstone | Plain stack (contrast #5 monotonic stack) |
| Active time vs. peak concurrency | Sort + merge ranges vs. sort (t, +1/-1) deltas / min-heap | #6 Merge Intervals / Meeting Rooms II (#7) |
| Rolling top-K / leaderboard / cooldowns | Sliding deque + Counter + bounded heap | #2 + #7 Kth Largest heap |
cd path, calculator, quoted CSV | Plain stack; operator-precedence stack; in_quotes scan | Plain stack / state scan (outside the 20) |
mkdir / ls or wildcard prefix* | Segment or character Trie (dict tree) | #12 Implement Trie |
| Org chart manager / cost / permissions | N-ary post-order DFS up, or pre-order DFS down | #11 Diameter bottom-up (contrast top-down) |
Parallel build waves / ${var} cycles | Kahn in_degree BFS layers; 3-state memoized DFS | #14 Course Schedule + #13 layers |
| Deduplicate shared emails/contacts | Graph DFS components (batch) or Union-Find (streaming) | #15 Redundant Connection |
| Closest server / warehouse on grid | Multi-source BFS from all 0 sources at once | #13 Rotting Oranges (#16 if weighted) |
Continue at Learn by rebuilding.