Choosing the right data structure is half the solution to any coding problem. In interviews, the first question is always: “What data structure should I use?” A wrong choice leads to slow solutions or unnecessary complexity. In this article, you will learn a decision framework for choosing the right data structure, see head-to-head comparisons, and get a complete cheat sheet you can reference any time.
This article covers everything from our first 9 articles in the series.
The Decision Framework
When you see a problem, ask yourself these questions in order:
1. What do I need to do most often?
| If you need to… | Use… |
|---|---|
| Access by index | Array |
| Look up by key | Hash map |
| Insert/delete at ends | Stack or Queue |
| Insert/delete in the middle | Linked list |
| Always get min or max | Heap (priority queue) |
| Search by prefix | Trie |
| Check connectivity | Union-Find or Graph + BFS/DFS |
| Maintain sorted order | BST or sorted array |
2. What are my constraints?
| Constraint | Implication |
|---|---|
| Must be O(1) lookup | Hash map or hash set |
| Must be sorted | BST, sorted array, or heap (partial) |
| Elements arrive one at a time | Heap or Union-Find |
| Need shortest path | Graph + BFS |
| Need to explore all possibilities | Graph + DFS or Backtracking |
3. Am I storing relationships or just values?
- Just values: Array, hash set, heap
- Key-value pairs: Hash map
- Hierarchical data: Tree
- Connections between items: Graph
- Groups of items: Union-Find
- Strings with shared prefixes: Trie
Time Complexity Comparison
Here is a side-by-side comparison of all data structures and their operation costs.
Core Operations
| Data Structure | Access | Search | Insert | Delete |
|---|---|---|---|---|
| Array | O(1) | O(n) | O(n) | O(n) |
| Linked List | O(n) | O(n) | O(1)* | O(1)* |
| Stack | O(n) | O(n) | O(1) | O(1) |
| Queue | O(n) | O(n) | O(1) | O(1) |
| Hash Map | O(1) avg | O(1) avg | O(1) avg | O(1) avg |
| Hash Set | - | O(1) avg | O(1) avg | O(1) avg |
| BST (balanced) | O(log n) | O(log n) | O(log n) | O(log n) |
| Min/Max Heap | O(1)** | O(n) | O(log n) | O(log n) |
| Trie | - | O(m) | O(m) | O(m) |
| Union-Find | - | O(1)*** | O(1)*** | - |
* If you have a reference to the node. Otherwise O(n) to find it first.
** Peek only (min or max). Arbitrary access is O(n).
*** Amortized with path compression and union by rank. m = length of the string (used in the Trie row).
Space Complexity
| Data Structure | Space |
|---|---|
| Array | O(n) |
| Linked List | O(n) |
| Stack / Queue | O(n) |
| Hash Map / Hash Set | O(n) |
| BST | O(n) |
| Heap | O(n) |
| Trie | O(N * M) where N = words, M = avg length |
| Graph (adj list) | O(V + E) |
| Union-Find | O(n) |
Head-to-Head Comparisons
Array vs Linked List
| Array | Linked List | |
|---|---|---|
| Access by index | O(1) | O(n) |
| Insert at beginning | O(n) | O(1) |
| Insert at end | O(1) amortized | O(1) with tail pointer |
| Memory | Contiguous, cache-friendly | Scattered, extra pointer overhead |
| Use when | Random access needed | Frequent insert/delete at head |
In practice: arrays (and dynamic arrays like ArrayList, list, slice) are almost always better because of CPU cache efficiency. Use linked lists only when you need O(1) insert/delete at known positions.
Hash Map vs BST
| Hash Map | BST (balanced) | |
|---|---|---|
| Search | O(1) average | O(log n) |
| Insert | O(1) average | O(log n) |
| Sorted order | No | Yes (inorder traversal) |
| Range queries | No | Yes |
| Worst case | O(n) with bad hash | O(log n) guaranteed |
| Use when | Fast lookup, no order needed | Need sorted data or range queries |
Heap vs Sorted Array
| Heap | Sorted Array | |
|---|---|---|
| Get min/max | O(1) | O(1) |
| Insert | O(log n) | O(n) |
| Delete min/max | O(log n) | O(1) or O(n) |
| Get kth element | O(k log n) | O(1) |
| Use when | Need min/max with dynamic inserts | Data is static or rarely changes |
Stack vs Queue
| Stack (LIFO) | Queue (FIFO) | |
|---|---|---|
| Order | Last in, first out | First in, first out |
| Use when | Undo operations, DFS, matching brackets | BFS, scheduling, processing in order |
BFS vs DFS on Graphs
| BFS | DFS | |
|---|---|---|
| Uses | Queue | Stack / Recursion |
| Finds | Shortest path (unweighted) | All paths, cycles |
| Space | O(width of graph) | O(depth of graph) |
| Use when | Shortest path, level-order | Cycle detection, topological sort, backtracking |
Trie vs Hash Set (for strings)
| Trie | Hash Set | |
|---|---|---|
| Exact search | O(m) | O(m) average |
| Prefix search | O(m) | Not possible |
| Autocomplete | Natural | Need extra work |
| Space | Higher | Lower |
| Use when | Prefix queries needed | Only exact match needed |
Union-Find vs Graph DFS
| Union-Find | Graph DFS | |
|---|---|---|
| Dynamic connectivity | O(1) amortized | Must rebuild |
| Connected components count | O(1) | O(V + E) |
| Shortest path | Cannot do | BFS can |
| Use when | Edges added over time | Need traversal or paths |
Common Interview Patterns and Their Data Structures
Here are the most common interview patterns and which data structure solves them best.
Pattern 1: “Find something in O(1)”
Use a hash map or hash set. If you need O(1) lookup, hashing is your tool.
Examples: Two Sum, Contains Duplicate, First Unique Character
Pattern 2: “Top K” or “Kth largest/smallest”
Use a heap. Keep a heap of size k.
Examples: Kth Largest Element, Top K Frequent Elements, K Closest Points
Pattern 3: “Valid parentheses” or “Matching pairs”
Use a stack. Push opening brackets, pop when you see closing brackets.
Examples: Valid Parentheses, Min Stack, Daily Temperatures
Pattern 4: “Level-by-level” or “Shortest path”
Use BFS with a queue.
Examples: Binary Tree Level Order, Shortest Path in Grid, Word Ladder
Pattern 5: “Explore all paths” or “Find all combinations”
Use DFS with backtracking.
Examples: Permutations, Subsets, Word Search, N-Queens
Pattern 6: “Connected components” or “Group items”
Use Union-Find if edges come dynamically. Use DFS/BFS on a static graph.
Examples: Number of Islands, Accounts Merge, Redundant Connection
Pattern 7: “Autocomplete” or “Prefix matching”
Use a trie.
Examples: Implement Trie, Word Search II, Search Suggestions
Pattern 8: “Sorted data with insert/delete”
Use a balanced BST (TreeMap/TreeSet in Kotlin/Java, SortedList in Python).
Examples: Sliding Window Median, My Calendar, Data Stream as Disjoint Intervals
Pattern 9: “Process elements in order of priority”
Use a heap (priority queue).
Examples: Merge K Sorted Lists, Task Scheduler, Reorganize String
Pattern 10: “Sliding window with min/max”
Use a deque (monotonic queue).
Examples: Sliding Window Maximum, Shortest Subarray with Sum at Least K
Quick Decision Flowchart
Follow this flowchart when you face a new problem:
Need O(1) lookup by key?
YES -> Hash Map / Hash Set
NO -> Continue
Need min/max repeatedly?
YES -> Heap
NO -> Continue
Need sorted order?
YES -> BST / Sorted Array
NO -> Continue
Working with strings and prefixes?
YES -> Trie
NO -> Continue
Need to track connected groups?
YES -> Union-Find
NO -> Continue
Working with a graph or grid?
YES -> Need shortest path?
YES -> BFS
NO -> DFS
NO -> Continue
Need LIFO (undo, matching)?
YES -> Stack
NO -> Continue
Need FIFO (scheduling, ordering)?
YES -> Queue
NO -> Continue
Default -> Array
Real-World Examples
Here is what powers real systems behind the scenes:
| System | Data Structure | Why |
|---|---|---|
| Database index | B-Tree (balanced tree) | Fast range queries on disk |
| Google Search autocomplete | Trie | Fast prefix matching |
| Task scheduler (OS) | Priority queue (heap) | Always run highest priority task |
| Social network “friends” | Graph | Represent connections |
| DNS lookup cache | Hash map | O(1) domain-to-IP mapping |
| Undo/Redo in editors | Stack | LIFO order matches undo behavior |
| Print queue | Queue | FIFO order |
| Network routing | Graph + Dijkstra (heap) | Shortest path with weights |
| Network connectivity check | Union-Find | Track which computers are in the same subnet |
Common Mistakes
Using a sorted array when you need frequent inserts. Insert into a sorted array is O(n). Use a heap or BST instead.
Using DFS when BFS gives shortest path. DFS does not guarantee shortest path in unweighted graphs. Use BFS.
Using a hash map when you need sorted iteration. Hash maps are unordered. Use a BST or sort the keys separately.
Implementing a linked list when an array works. Arrays are almost always faster due to cache locality. Only use linked lists when you truly need O(1) insert/delete at known positions.
Forgetting that hash map worst case is O(n). Rare, but possible with bad hash functions. Mention this in interviews to show you understand trade-offs.
Interview Strategy
When the interviewer gives you a problem:
- Identify the core operation. What do you do most? Lookup? Insert? Get min? Traverse?
- Pick the data structure. Use the decision framework above.
- State it out loud. “I will use a hash map because I need O(1) lookups.”
- Consider trade-offs. “A heap gives me O(log n) insert and O(1) peek, which is better than sorting every time.”
- Code it. Use your language’s built-in data structures — do not implement from scratch unless asked.
Interviewers care more about you choosing the right data structure than writing perfect code. A correct choice with a minor bug beats a wrong data structure with perfect syntax.
Practice Problems — Full Review
Go back and practice these problems. They cover all 9 data structures:
| Problem | Data Structure | LeetCode # |
|---|---|---|
| Two Sum | Hash Map | #1 |
| Valid Parentheses | Stack | #20 |
| Merge Two Sorted Lists | Linked List | #21 |
| Binary Tree Level Order | Queue + BFS | #102 |
| Kth Largest Element | Heap | #215 |
| Number of Islands | Graph + DFS or Union-Find | #200 |
| Implement Trie | Trie | #208 |
| Course Schedule | Graph + Topological Sort | #207 |
| Redundant Connection | Union-Find | #684 |
| Top K Frequent Elements | Hash Map + Heap | #347 |
What’s Next?
Congratulations — you now know all the core data structures. In the next part of this series, we move to Algorithms, starting with Sorting Algorithms. You will learn the most important sorts, their trade-offs, and when each one is the best choice.
Next: DSA Tutorial #11: Sorting Algorithms
Full series: DSA from Zero to Interview Ready