synopsis · Expert · chapter 37
Design Data Structures
10 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A design question = an API + a cost per method. Pick one structure per method's question, glue them with an invariant, keep them in sync on every call.
- use it when
"Design X" or "implement the class" with methods like insert, get, pop, ls — and targets like O(1) or O(log n) per call.
- template
Routine: API → cost per method → structures → invariant as a comment → code each method → dry-run a script of calls.
- template
O(1) delete:
values.set(i, last); indexOf.put(last, i); values.remove(size - 1); indexOf.remove(val); - cost
RandomizedSet O(1) avg · FreqStack O(1) avg · TimeMap set O(1) amortized, get O(log v) · file system O(depth · log c) · DetectSquares O(one column).
- trap
Swap-with-last: update the moved element's index, and remove val from the map last — or deleting the last element breaks.
- trap
list.remove(5)on aList<Integer>removes index 5, not the value 5. And"/a".split("/")starts with an empty string. - pro tip
Most frequent, newest wins →
count → stackgroups + a maxFreq that moves by ±1. Value at time t → floor search in a time-sorted history. - pro tip
Paths → a trie of names (TreeMap children give sorted ls). Shapes from stored points → count copies, loop over one column.
- pro tip
Say average for HashMap and amortized for ArrayList.add. Then dry-run: empty, delete the last element, duplicates, a tie.
Shaky on a card? Open the chapter or flip its recall cards.