Data Structures You Will Reuse
Goal: Choose a structure because its operations match the problem, not because it is familiar.
Array and string
Contiguous indexed storage gives O(1) access. Inserting in the middle shifts items. Use two indices, prefix state, or a window when order and locality matter.
Hash map and set
A map stores key→value state; a set stores membership. They turn repeated scans into expected constant-time lookup. Define an exact key and watch memory use.
Stack and queue
A stack is last-in-first-out and models nesting or unresolved future relationships. A queue is first-in-first-out and gives breadth-first layers. A deque supports efficient updates at both ends.
Heap
A heap exposes one extreme efficiently: O(1) peek, O(log n) insert/remove. A size-k min-heap keeps the k largest values; a max-heap keeps the k smallest.
Linked list
Nodes connect by references, so local relinking is O(1), but locating a position costs O(n). Save next before changing links.
Tree and graph
A tree is a connected acyclic hierarchy; recursion often summarizes subtrees. A graph generalizes relationships and may be directed, cyclic, disconnected, or weighted. Match BFS, DFS, topological sort, Dijkstra, or DSU to the question.
Dynamic programming table
A DP cell caches a subproblem. Write down the exact meaning of dp[i] or dp[i][j], base cases, transition, and iteration order.
Choosing quickly
| Need | Starting point | |---|---| | Membership/counts | Set / map | | Next greater item | Monotonic stack | | First feasible value | Binary search | | Shortest unweighted path | BFS | | Repeated best candidate | Heap | | Prefix dictionary | Trie | | Repeated subproblem | Memoization / DP |