Classic Data-Structure Drills: Cache, Trie, Heaps, Graphs
Data Structure DesignModel answerLast updated
Work through fifteen core algorithm patterns—LRU cache, trie, two-pointers, sliding window, topological sort, and more—naming invariants before coding.
This is a rapid-fire pattern drill rather than a single puzzle. You will be given a set of fifteen short problems covering the most common data-structure and algorithm archetypes. For each one you should:
- Identify the reusable pattern it belongs to (hashing, two pointers, sliding window, stack, heap, graph traversal, etc.).
- State the invariant the pattern maintains.
- Give a working solution with its time and space complexity.
- Call out the edge cases that would break a naive implementation.
The problems:
-
Fixed-capacity recency cache. Implement
get(key)andput(key, value), both O(1) average. When full, discard the item used least recently. -
Randomized set. Support
insert(val),remove(val)andgetRandom()(uniformly random element) in O(1) average time. -
Prefix dictionary. Support
insert(word),search(word)(exact word) andstartsWith(prefix). -
Top k frequent values. Given
nums = [1,1,1,2,2,3]andk = 2, return the two most frequent values, e.g.[1,2]in any order. -
Product of all others. For
[1,2,3,4]return[24,12,8,6]without using division, in O(n). -
Trapped rainwater. Given non-negative heights such as
[0,1,0,2,1,0,1,3,2,1,2,1], compute the volume of water held between the bars. -
Largest container. Given vertical line heights, pick two lines maximizing the area they hold with the x-axis.
-
Longest substring without repeats. For
"abcabcbb"return3. -
Group anagrams. Group
["eat","tea","tan","ate","nat","bat"]into letter-equivalent clusters. -
Decode nested repeats. Decode
"3[a2[c]]"into"accaccacc". -
Count islands. Given a grid of land and water, count 4-connected land components.
-
Course scheduling. Given
ncourses and prerequisite pairs, decide whether all can be completed (i.e., the prerequisite graph is acyclic). -
Merge k sorted lists. Merge lists like
1->4->5,1->3->4,2->6into1->1->2->3->4->4->5->6. -
In-place matrix rotation. Rotate an n×n matrix 90° clockwise without allocating another matrix.
-
Longest mountain. In
[2,1,4,7,3,2,5], the longest strictly-increasing-then-strictly-decreasing contiguous run is[1,4,7,3,2], length5.
Hints
Hint 1
Fifteen problems, roughly eight patterns. Map each problem to a pattern before writing any code, then say the invariant out loud.
Hint 2
Several problems are secretly two-pointer scans (water trapping, container); the correctness argument always hinges on which side you can safely discard.
Hint 3
For O(1) random access plus O(1) removal, keep a dense array plus a value-to-index map and swap the victim with the last element before popping.
Hint 4
Carry the edge cases as a checklist: zeros in the product problem, capacity 0 in the cache, multi-digit repeat counts, empty grids and lists, plateaus in the mountain scan.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Treat this as fifteen small design conversations. For each problem the interviewer wants the pattern name, the invariant, a correct implementation, complexity, and the edge cases.
Pattern map. (1) hash map plus doubly linked list. (2) dense array plus index map. (3) trie. (4) frequency count plus bucketing by count. (5) prefix/suffix products. (6) two pointers from both ends. (7) two pointers shrinking the width. (8) sliding window with last-seen indices. (9) canonical key per word. (10) explicit stack of (string, repeat) frames. (11) flood fill. (12) Kahn's topological sort. (13) k-way merge with a min-heap. (14) transpose then reverse rows. (15) single pass with up/down phases.
The tricky correctness arguments.
- Randomized set: the array must stay dense for uniform sampling, so removal swaps the target with the last element and fixes the moved element's index. Removing the last element is a swap-with-self; handle it by updating the map before deleting.
- Trapped water: if the running left max is smaller than the right max, the water at the left pointer is bounded by the left max alone, so that cell can be finalized and the pointer advanced. Mirror the argument on the right.
- Container: when the left line is shorter, every container formed by moving the left line inward is both narrower and no taller, so the left line can never be part of a better answer — discard it.
- Top k: frequencies never exceed n, so bucket values by count and scan buckets from n downward; this is O(n) rather than O(n log n).
- Course scheduling: Kahn's algorithm only ever releases nodes whose indegree has dropped to zero. A cycle never reaches zero, so "processed count equals n" is exactly "acyclic".
- Longest mountain: after a descent, leave the index on the valley — it can start the next mountain. Plateaus (equal neighbors) invalidate a run because neither phase is strict.
- Matrix rotation: the clockwise mapping sends
(i, j)to(j, n-1-i); transpose plus row reversal realizes it in place.
Reference implementations (Python, condensed).
from collections import OrderedDict, Counter
import random, heapq
class LRUCache: # 1
def __init__(self, cap): self.cap, self.d = cap, OrderedDict()
def get(self, k):
if k not in self.d: return -1
self.d.move_to_end(k); return self.d[k]
def put(self, k, v):
self.d[k] = v
self.d.move_to_end(k)
if len(self.d) > self.cap: self.d.popitem(last=False)
class RandomizedSet: # 2
def __init__(self): self.v, self.i = [], {}
def insert(self, x):
if x in self.i: return False
self.i[x] = len(self.v); self.v.append(x); return True
def remove(self, x):
if x not in self.i: return False
j, last = self.i[x], self.v[-1]
self.v[j] = last; self.i[last] = j
self.v.pop(); del self.i[x]; return True
def getRandom(self): return random.choice(self.v)
def top_k_frequent(nums, k): # 4
counts = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for val, c in counts.items(): buckets[c].append(val)
out = []
for c in range(len(buckets) - 1, 0, -1):
out.extend(buckets[c])
if len(out) >= k: return out[:k]
def product_except_self(a): # 5
n, out, suffix = len(a), [1] * len(a), 1
for i in range(1, n): out[i] = out[i-1] * a[i-1]
for i in range(n-1, -1, -1):
out[i] *= suffix; suffix *= a[i]
return out
def trap(h): # 6
l, r, lm, rm, total = 0, len(h)-1, 0, 0, 0
while l < r:
if h[l] < h[r]:
lm = max(lm, h[l]); total += lm - h[l]; l += 1
else:
rm = max(rm, h[r]); total += rm - h[r]; r -= 1
return total
def max_area(h): # 7
l, r, best = 0, len(h)-1, 0
while l < r:
best = max(best, (r-l) * min(h[l], h[r]))
if h[l] < h[r]: l += 1
else: r -= 1
return best
def longest_unique(s): # 8
last, left, best = {}, 0, 0
for i, c in enumerate(s):
if last.get(c, -1) >= left: left = last[c] + 1
last[c] = i; best = max(best, i - left + 1)
return best
def decode(s): # 10
stack, cur, num = [], "", 0
for c in s:
if c.isdigit(): num = num*10 + int(c)
elif c == '[': stack.append((cur, num)); cur, num = "", 0
elif c == ']':
prev, rep = stack.pop(); cur = prev + rep * cur
else: cur += c
return cur
def num_islands(g): # 11
if not g: return 0
R, C, seen, cnt = len(g), len(g[0]), set(), 0
for i in range(R):
for j in range(C):
if g[i][j] == '1' and (i, j) not in seen:
cnt += 1; st = [(i, j)]; seen.add((i, j))
while st:
x, y = st.pop()
for dx, dy in ((1,0),(-1,0),(0,1),(0,-1)):
nx, ny = x+dx, y+dy
if 0 <= nx < R and 0 <= ny < C and g[nx][ny] == '1' \
and (nx, ny) not in seen:
seen.add((nx, ny)); st.append((nx, ny))
return cnt
def can_finish(n, prereqs): # 12
adj, indeg = [[] for _ in range(n)], [0]*n
for a, b in prereqs:
adj[b].append(a); indeg[a] += 1
q = [i for i in range(n) if indeg[i] == 0]; done = 0
while q:
u = q.pop(); done += 1
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
return done == n
def rotate(m): # 14
n = len(m)
for i in range(n):
for j in range(i+1, n): m[i][j], m[j][i] = m[j][i], m[i][j]
for row in m: row.reverse()
Complexities. Cache and randomized set: O(1) per op. Trie: O(L) per op. Top k: O(n). Product, trap, container, substring, mountain: O(n) time, O(1) (or alphabet-sized) extra space. Anagrams: O(n·L). Decode: O(output length). Islands: O(R·C). Courses: O(V+E). Merge k lists: O(N log k). Rotation: O(n²).
Edge cases worth stating aloud. Capacity 0, and re-put on an existing key, for the cache; removing the sole element in the randomized set; ties in top-k; zeros in the product problem (prefix/suffix handles them without special cases, which is exactly why the no-division rule is natural); arrays shorter than 3 or 2 for trap/container; empty string and the >= left check in the window; multi-digit counts and letters outside brackets in decode; empty grid and 4-directional adjacency in islands (use iterative flood fill to dodge recursion limits); self-loops and duplicate prerequisites in courses; empty lists and k = 0 in the merge (also add an index tie-breaker, since list nodes are not comparable); monotone arrays and plateaus in the mountain scan. If asked to avoid OrderedDict, write the doubly linked list with sentinel head and tail plus small unlink/append helpers — identical logic, more code.