Lesson 9 of 27From idea to plan
Choosing Data Structures
List the operations your plan needs, then pick the structure that makes the most frequent ones cheap.
Choosing a data structure is not about which one you like. It is a small piece of accounting. Write down the operations your algorithm performs, note how often each happens, and pick the structure where the frequent ones are cheapest. Get this right and the complexity follows. Get it wrong (a list where you needed a set) and a correct algorithm turns quietly quadratic. Data Structures Overview in the Algorithms & Patterns course has the full cost of each structure; this lesson is about using those costs to decide.
Start from the operations, not the structure
Before naming any structure, describe what your plan does to its data in plain verbs:
- "For each number, check whether I have seen its complement." → membership test, n times.
- "Repeatedly take the smallest and add new items." → min and insert, many times.
- "Push an opener, and look at and remove the latest one on a closer." → last-in, first-out.
- "Take the oldest item, add its neighbours to the back." → first-in, first-out.
- "Count how many times each value appears." → increment by key.
Each verb has a cost in each structure. The best structure is the one whose costs match your most frequent verbs.
The cost table
Average costs. n is the number of items stored.
| Structure | Access by index | Search by value | Add / remove at end | Add / remove at front | Min or max | Kept in order? |
|---|---|---|---|---|---|---|
Array / Python list | O(1) | O(n) | O(1) | O(n) | O(n) | no |
| Sorted array | O(1) | O(log n) | O(n) insert | O(n) | O(1) | yes |
| Hash map / set | n/a | O(1) | O(1) insert / delete | n/a | O(n) | no |
| Stack (a list used at one end) | top only | O(n) | O(1) push / pop | n/a | O(n) | no |
Queue / deque | O(1) ends | O(n) | O(1) | O(1) | O(n) | no |
Binary heap (heapq) | n/a | O(n) | O(log n) push / pop | n/a | O(1) peek | partly |
| Balanced BST / sorted container | O(log n) | O(log n) | O(log n) | O(log n) | O(log n) | yes |
| Linked list | O(n) | O(n) | O(1) with a tail | O(1) | O(n) | no |
A few more you will meet: a trie answers "does any word start with this prefix?" in O(length of the prefix), and union-find answers "are these two connected?" and merges groups in nearly O(1).
queue.pop(0) to take the next node. On a graph with 10^5 nodes, what is the problem?Watching the right structure work
Counting is the most common job in these problems. Here is a hash map counting the letters of "banana", then answering questions instantly.
Read b. Not in the map, so store b → 1. O(1).
When keys are small integers or a fixed alphabet (lowercase letters), an array of 26 counts does the same job with less overhead. The constraints tell you which you can use.
Queues in Python and JavaScript
The pop(0) trap above is common enough to deserve a standing rule for each language.
- Python: use
collections.dequefor any queue.appendandpopleftare O(1). Alistis fine as a stack (appendandpopat the end) but never as a queue. Indexing into the middle of a deque is O(n), so do not use it as a random-access array. - JavaScript: there is no built-in deque.
pushis amortised O(1), butshiftmoves every remaining element. For BFS, keep a head index and readqueue[head++]. The array grows, but each item is touched once, so the total is O(n). If memory matters on a long-running queue, slice off the consumed front now and then.
Press Run (⌘ Enter) to see what happens.Exact timings depend on the engine, but the gap is the point: one loop is O(n²) and the other is O(n). In an interview, write the head-index version and say why in one sentence.
Ordered structures your language does not have
The cost table lists a balanced BST, but neither Python nor JavaScript ships one in its standard library. Java has TreeMap and TreeSet, and C++ has std::set and std::map. When your plan needs "the smallest key greater than x" while items are inserted and removed, you have four practical options:
bisecton a sorted list. O(log n) to find, O(n) to insert or delete. With up to about 10^4 changes this is usually fast enough, because the shift is a fast memory move. Say the O(n) out loud anyway.- A heap, if you only need one end. "Smallest remaining" does not need full order. Most "I need a TreeMap" moments in Python are really heap problems.
sortedcontainers.SortedList. Not standard library. LeetCode's Python environment has historically included it, but many OA platforms do not, so ask or check before you rely on it.- Offline tricks. If you know all values up front, compress them to ranks
0..m-1and use a Fenwick tree for counts and order statistics. Fenwick Trees, Segment Trees and Sorted Containers in the Algorithms & Patterns course covers this.
The interviewer usually cares more that you know which operation needs O(log n) than which library provides it. "In Java I would use a TreeMap here. In Python I will use a sorted list with bisect and note the O(n) insert" is a strong answer. Your Language's Interview Toolkit lists what each platform has installed.
Grids: a 2D array or a dict of tuples
Grid problems give you a choice. A 2D array (grid[r][c]) is compact, O(1) to index, and cheap to copy. A dict or set keyed by (r, c) handles grids with no fixed size, sparse grids where most cells are empty, and coordinates that go negative.
- Bounded and dense (an m × n board, islands, shortest path in a maze): use a 2D array. It is faster, and the bounds check
0 <= r < mis explicit. - Unbounded or sparse (an infinite Game of Life, a robot walking from the origin, "visited" cells of a huge board): use a set of tuples. Memory follows the cells you touch, not the board size.
- A
visitedmatrix of booleans beats avisitedset on a dense grid: no hashing, and no tuple allocation per cell.
One trap catches people in both languages. In Python, [[0] * n] * m makes m references to the same row. In JavaScript, new Array(m).fill([]) does the same. Build rows separately: [[0] * n for _ in range(m)] or Array.from({ length: m }, () => new Array(n).fill(0)).
What does this print?
grid = [[0] * 3] * 2 grid[0][0] = 1 print(grid)
Matching needs to structures
Match what your plan needs to the structure that makes it cheap.
What does this print?
from collections import deque q = deque([1, 2]) q.append(3) q.appendleft(0) q.popleft() q.pop() print(list(q))
When two needs pull in different directions
Sometimes your plan needs two operations that no single structure makes cheap. Then you combine structures.
- LRU cache: O(1) lookup by key and O(1) "move to most recent". A hash map plus a doubly linked list (or Python's
OrderedDict). - Min Stack: a stack that can also report its minimum in O(1). A second stack that stores the minimum so far at each level.
- Running median: the middle value while numbers stream in. Two heaps, a max-heap for the lower half and a min-heap for the upper half.
- Top k frequent: a hash map for the counts, then a heap of size k (or buckets by count) to pick the winners.
Put the structure-choosing routine in order.
- Tap the steps below in the right order.
bisect.insort risky for 10^5 numbers?Designing a structure from two
Design-a-structure questions (Insert Delete GetRandom O(1), LRU Cache, Stock Price Fluctuation) are the same accounting done deliberately: list each required operation, notice that no single structure makes all of them cheap, and give each structure the job it is good at. The map is almost always one half, because it answers "where is this key?" in O(1).
Map + array: Insert Delete GetRandom O(1). An array makes a random pick O(1) (random.choice), but deleting from the middle is O(n). A map from value to its index fixes that: to delete, look up the index, swap the last element into that slot, update the moved element's index in the map, then pop the end. Order is lost, which the problem allows. The swap is the whole trick, and forgetting to update the moved element's index is the usual bug.
Map + heap with lazy deletion. A heap cannot find and remove an arbitrary entry cheaply. So do not try. When a value changes, push the new entry and leave the old one in the heap. Keep the truth in a map. When you read the top, check it against the map and pop it if it is stale. Each entry is pushed once and popped at most once, so the total stays O(n log n).
Press Run (⌘ Enter) to see what happens.The same idea appears as "delayed deletion" in sliding window median and in Dijkstra, where you skip a popped node whose distance is already final. Decoding Strings, Math, Matrices and Design walks through more of these.
Practice
You only ever need the smallest of your k candidates. Pick the structure that makes that cheap.
Kth Largest Element
Given a list of integers nums and a number k, return the kth largest value. This is the kth largest in sorted order, so duplicates count separately.
nums = [3, 2, 1, 5, 6, 4], k = 2 → 5
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4 → 4Try to beat sorting the whole list.
Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
- operation cost
- How expensive one verb (search, insert, min, pop front) is in a given structure. Choose the structure where frequent verbs are cheap.
- hash set
- Stores values for O(1) average membership tests. No order, no duplicates.
- deque
- A double-ended queue: O(1) add and remove at both ends. Use it for BFS instead of
list.pop(0). - binary heap
- Gives the min (or max) in O(1) and inserts or removes in O(log n). Python's
heapqis a min-heap. - lazy deletion
- Leaving outdated entries in a heap and discarding them when they reach the top, using a map as the source of truth.
- balanced BST
- A search tree kept shallow so search, insert, delete and next-larger are all O(log n). Java and C++ ship one; Python and JS do not.
- combined structure
- Two structures working together when no single one makes every needed operation cheap, like a map plus a linked list for an LRU cache.