Skip to content

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.

21 min read0/8 questions

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.

StructureAccess by indexSearch by valueAdd / remove at endAdd / remove at frontMin or maxKept in order?
Array / Python listO(1)O(n)O(1)O(n)O(n)no
Sorted arrayO(1)O(log n)O(n) insertO(n)O(1)yes
Hash map / setn/aO(1)O(1) insert / deleten/aO(n)no
Stack (a list used at one end)top onlyO(n)O(1) push / popn/aO(n)no
Queue / dequeO(1) endsO(n)O(1)O(1)O(n)no
Binary heap (heapq)n/aO(n)O(log n) push / popn/aO(1) peekpartly
Balanced BST / sorted containerO(log n)O(log n)O(log n)O(log n)O(log n)yes
Linked listO(n)O(n)O(1) with a tailO(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).

Quick check
A BFS uses a Python list as its queue and calls queue.pop(0) to take the next node. On a graph with 10^5 nodes, what is the problem?
Need a nudge? A hint rules out a wrong answer.

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.

Counting with a hash map

puthash("b") % 8 = 2

  1. 0empty
  2. 1empty
  3. 2"b":1
  4. 3empty
  5. 4empty
  6. 5empty
  7. 6empty
  8. 7empty

Read b. Not in the map, so store b → 1. O(1).

1/4

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.deque for any queue. append and popleft are O(1). A list is fine as a stack (append and pop at 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. push is amortised O(1), but shift moves every remaining element. For BFS, keep a head index and read queue[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.
JavaScript
// A queue with a head index: O(1) dequeue without shift()const queue = [];let head = 0;const enqueue = (x) => queue.push(x);const dequeue = () => queue[head++];const size = () => queue.length - head; enqueue("a"); enqueue("b"); enqueue("c");console.log(dequeue(), dequeue(), "left:", size()); // Rough timing: shift() moves every item, the head index does notconst n = 50000;let t = Date.now();const slow = Array.from({ length: n }, (_, i) => i);while (slow.length) slow.shift();console.log("shift loop ms:", Date.now() - t); t = Date.now();const fast = Array.from({ length: n }, (_, i) => i);let h = 0;while (h < fast.length) h++;console.log("head index ms:", Date.now() - t);
Output
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:

  1. bisect on 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.
  2. 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.
  3. 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.
  4. Offline tricks. If you know all values up front, compress them to ranks 0..m-1 and 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 < m is 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 visited matrix of booleans beats a visited set 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)).

Predict the outputPython

What does this print?

grid = [[0] * 3] * 2
grid[0][0] = 1
print(grid)
Need a nudge? Hints walk you through it.

Matching needs to structures

Match the pairs0/6 matched

Match what your plan needs to the structure that makes it cheap.

Choose an item, then its match on the other side.
Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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.
Quick check
You need the k-th largest of 10^5 numbers, with k small. Which plan is best?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Put the structure-choosing routine in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Numbers arrive one by one and after each you must report the current median. Why is a sorted Python list with bisect.insort risky for 10^5 numbers?
Need a nudge? A hint rules out a wrong answer.

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).

Python
import heapq class PriceTracker: """Latest price per timestamp, plus the current max. Prices can be corrected.""" def __init__(self): self.price = {} # timestamp -> latest price (the truth) self.heap = [] # (-price, timestamp), may hold stale entries def update(self, ts, p): self.price[ts] = p heapq.heappush(self.heap, (-p, ts)) # do not hunt for the old entry def maximum(self): while -self.heap[0][0] != self.price[self.heap[0][1]]: heapq.heappop(self.heap) # stale: the map disagrees, drop it return -self.heap[0][0] t = PriceTracker()t.update(1, 10); t.update(2, 5)print(t.maximum())t.update(1, 3) # correction: timestamp 1 was really 3print(t.maximum())print("heap size:", len(t.heap))
Output
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.

Quick check
In Insert Delete GetRandom O(1), why do you swap the element to delete with the last element before popping?
Need a nudge? A hint rules out a wrong answer.

Practice

You only ever need the smallest of your k candidates. Pick the structure that makes that cheap.

ChallengeMedium

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  →  4

Try to beat sorting the whole list.

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
def find_kth_largest(nums: list[int], k: int) -> int: # Keep only the k largest values seen so far in a min-heap. pass
Key terms
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 heapq is 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.