Data structures for LLD
medium 45 minInside a class the choice of container decides which method is fast, which is correct, and which lock is needed.
Video lesson · Chapter 1 of 6
Make a prediction
Data structures for LLD
1:01Reel
Theory
Read or listen first. About 2 min.
What it is
In a design round a data structure is a private decision inside a class. The public methods say what can be asked. The container decides how long an answer takes, in which order things come out, and what can go wrong when two threads ask at once.
The way to choose is always the same. List the calls. Mark the ones that happen often or that must be exact. For each, name the question it asks: by key, by range, by smallest, by order of arrival, by last in, by yes or no. Each question has a natural container.
Many classes need two questions answered fast. Then they hold two containers over the same objects, and one method updates both. This pair is called a composite structure. Its danger is that the two can disagree.
Why it exists
Interviewers ask why this structure in almost every round. The answer is a call and its cost, not a favourite: take the nearest free spot, many times a minute, so a heap.
The wrong container also hides bugs. A list that is searched by hand gives a slow program. A list that is sorted once and then changed gives a wrong program.
And it protects you from too much. With thirty items a list with a loop is the best structure of all: short, clear and fast enough. You should be able to say the number at which that changes.
A short history
1953
Hans Peter Luhn writes an internal IBM memorandum that uses hashing with chaining, the idea behind today's hash maps.
1962 or 1963
Edsger Dijkstra invents the semaphore while working on an operating system for the Electrologica X8.
1964
J. W. J. Williams introduces heapsort, and with it the binary heap as a structure of its own.
1970
Rudolf Bayer and Edward McCreight present the B-tree, the ordered structure behind most database indexes.
1974
Raphael Finkel and J. L. Bentley name the quadtree, a tree for points in two dimensions.
1989
William Pugh describes skip lists, ordered lists with fast search that need no rebalancing.
Words to know
- Access pattern
- Which calls happen, how often, and by which question.
- Index
- A second container that finds the same objects by another question.
- Amortised
- Cheap on average over many calls, although a single one can be slow.
- Lazy deletion
- Leave an outdated entry in a heap and skip it when it comes out.
- Invariant
- A fact about the containers that is true after every public call.
- Check then act
- Two steps that must not be separated by another thread.
- Bounded queue
- A queue with a limit, so that a fast producer has to wait.
- Semaphore
- A counter of permits. It knows how many, not which.
- Copy on write
- Readers see a finished copy, a writer replaces the whole copy.
How it works
Step through the idea, or press Play.
List the calls. Which are often, which must be exact?
Understand it
Start here
The kitchen garden shed
Noor has a small kitchen garden and one shed. Everything in the shed lies, hangs or stands in some container. The right container is the one that makes the next question easy.
Pile, hooks, rack, pyramid, row, pegs. Each answers one question well.
Step 1
From question to container
What do you need to ask?
| I need | Container | Cost | Careful |
|---|---|---|---|
| Instant lookup by id | Hash map | O(1) on average | No order. Keys must not change while inside |
| Items in a range, next larger, previous | Sorted map (TreeMap, sorted list) | O(log n) to find, then k for k results | One dimension only |
| Points within 5 miles | Grid of cells, quadtree, or a spatial index | Depends on how points are spread | A sorted map of latitudes alone is not enough |
| Highest or lowest priority first | Heap | O(1) to look, O(log n) to add or take | Not searchable, not fully sorted |
| True or false for very many items | Bit set | 1 bit each, O(1) by number | Finding a free one scans words, 64 bits at a time |
| Lookup and order of insertion | Linked hash map | O(1) | Java keeps insertion order, or access order if asked |
| Last in first out, first in first out | Stack, queue (a deque does both) | O(1) at the ends | A Python list is slow at the front |
| Is it there already? | Hash set | O(1) on average | Needs equality that fits |
| Newest k of many sorted lists | Heap of list heads (k-way merge) | O(log k) for each result | Holds one entry per list |
Decide in one minute
Six containers, one line each
Map
Ticket number to car. The default for anything with an identity.
Heap
Nearest free spot, next timer, smallest fare.
Deque
Waiting people, last ten actions, sliding window.
Sorted map
Bookings by start time. Free gap before and after.
Bit set
Seats of one row, spots of one floor.
Plain list
Up to a few dozen, read rarely. Say so and move on.
Step 2
Costs, with a size next to them
A cost without a size says little. Put the number of items beside it. The table counts comparisons for one call, rounded, for a list that is scanned and for a sorted or heap structure.
How many steps for one call?
| Items | Scan a list | Heap or sorted map: about log2 n | Hash map |
|---|---|---|---|
| 30 | up to 30 | about 5 | about 1 |
| 1,000 | up to 1,000 | about 10 | about 1 |
| 100,000 | up to 100,000 | about 17 | about 1 |
| 1,000,000 | up to 1,000,000 | about 20 | about 1 |
Good reasons
- Called for each arriving car, and there are 5,000 spots
- The answer must be the nearest, so order matters
- Thirty benches, so a loop is clearer
Weak reasons
- A heap is fast
- We always use a HashMap
- It is thread safe, so it is better
Worked example
A repair desk
People bring broken things to a repair desk. Each job has a number and a promised time. The desk is asked four things: show job 17, which job is most urgent, cancel job 17, who was first in line for the sewing bench.
Calls first, containers second
| Call | How often | Question | Container |
|---|---|---|---|
| find(number) | often | by id | Map from number to Job |
| next_urgent() | often | smallest promised time | Heap of (time, number) |
| cancel(number) | sometimes | by id, inside a heap | Map, and lazy deletion in the heap |
| join(bench), call(bench) | often | order of arrival | One deque per bench |
One list for everything
1/3It works
A desk with a list. Each method walks through it. With twenty jobs that is fine.
has (lives on)uses
Three private containers, one owner
1/4The truth is in one place
The map holds the jobs. Whatever the other containers say, a job exists only if it is here.
owns (dies together)has (lives on)
Repair desk: a map, a heap and deques
Containers are private fields, named after the question they answer.
import heapqfrom collections import dequefrom dataclasses import dataclass@dataclassclass Job: number: int thing: str promised: int open: bool = Trueclass RepairDesk: def __init__(self): self._by_number = {} self._by_time = [] self._lines = {} self._next = 1Lines 6 to 11
The job knows whether it is open. The heap does not need to know, and that keeps cancel cheap.
Pairs
Composite structures you will meet again
Two containers, one job
| Pair | Gives you | Used in |
|---|---|---|
| Hash map and doubly linked list | Lookup and move to front, both O(1) | LRU cache |
| Hash map and heap | Lookup and smallest, cancel by lazy deletion | Job scheduler, timers |
| Hash map and sorted set | Lookup and ranking or range | Leaderboards, auction |
| Map of deques | One line per group | Waiting lists, pub and sub |
| 2D array and stack | Square by position, undo of the last move | Chess |
| Bit set and map | First free number, who holds it | Parking lot |
| Array used as a ring | Last N items without allocation | Logger |
One call updates both
Step 3
Choosing the synchronisation tool
If several threads call the same object, the containers need protection. Again the call decides. Full explanations live in the concurrency pages. This is the short form for choosing.
What is your concurrency need?
Four tools, and the trap of each
| Tool | Use it for | Trap |
|---|---|---|
| Read-write lock | One writer, many readers, for example a catalogue. Many may read together | Worth it only for long or frequent reads. An LRU read moves an entry, so it is a write |
| Semaphore | A limited number, for example 50 parking spots or a connection pool | Counts permits. It does not say which spot, so you still need a safe container |
| Atomic integer | A simple counter or a request id, without a lock | Two atomics together are not atomic. For hot statistics Java has LongAdder |
synchronized, a lock, or a transaction | Several steps that must happen as one, for example a money transfer or check then act | A lock lives in one process. With two servers the database must decide |
| Blocking queue | Work from one thread to another | Without a bound it grows until memory is gone |
| Thread local | Data of one thread, for example a log context | In a thread pool it must be cleared, because threads are reused |
Code
How many, and which one
The most common mistake with a limited resource is to protect the number and forget the choice. Here are the three shapes you will write most often: a pool, a counter and a catalogue.
A pool needs two things: how many and which
1/3How many
The semaphore lets three threads in and makes the fourth wait.
owns (dies together)
Safe counters, safe pools, safe reads
The semaphore limits, the heap chooses, the lock protects the heap.
import heapqimport threadingclass BenchPool: def __init__(self, count): self._free = list(range(1, count + 1)) self._slots = threading.BoundedSemaphore(count) self._lock = threading.Lock() def take(self, timeout=None): if not self._slots.acquire(timeout=timeout): return None with self._lock: return heapq.heappop(self._free) def give(self, bench): with self._lock: if bench in self._free: raise ValueError(f"bench {bench} is already free") heapq.heappush(self._free, bench) self._slots.release()Lines 12 to 13
Wait for a permit first, outside the lock. If we waited inside, nobody could give a bench back and everything would stop.
Two threads, one free bench, no lock
Classic problems
Which container in which problem
| Problem | Hot call | Container and lock | Why |
|---|---|---|---|
| Elevator | next stop above me | Sorted set of floors for each direction | A heap gives the smallest, not the next above |
| Parking lot | nearest free spot | Heap or bit set per size, map by ticket, one lock | Take must be check and act |
| LRU cache | get and move to front | Hash map and linked list, one lock | Reads change the order |
| Movie booking | hold these seats | Map by seat, expiry heap, lock per show | All seats or none |
| Meeting scheduler | overlap with a time | Sorted map by start | Look at the one before and the one after |
| Feed | newest 20 of 300 people | Heap of 300 heads | 20 results cost about 20 times log 300 |
| Logger | append, never wait long | Bounded queue or ring buffer, one writer | The file is slow |
| Rate limiter | how many in the last minute | Deque of times per user | Old ones leave at the front |
Grading
Find the nearest free bench
5,000 spots, 10 arrivals a second, always give the lowest free number. What do you store?
BreaksA semaphore with 5,000 permits
- How
- acquire on arrival, release on leaving.
- Limit
- It knows that one is free, not which. Two cars get spot 1.
- Choose when
- Only together with a container.
WorksA list of booleans and a loop
- How
- Scan for the first False under a lock.
- Limit
- Up to 5,000 steps per arrival, 50,000 a second. It would do, and it holds the lock longer.
- Choose when
- Small lots. Say the number.
StrongA heap of free numbers, or a bit set, with a map by ticket
- How
- Pop is about 13 steps. A bit set scans 5,000 / 64, about 79 words.
- Limit
- Two containers must stay in step, so one class owns both.
- Choose when
- Choose the heap if order can change, the bit set if numbers are dense and fixed.
In the room
How to say it
Why this data structure?
Interviewer
You wrote a heap. Why?
You
The call that happens most is: give me the most urgent open job. A heap gives that in log n, and adding is log n as well.
- Call
- Question
- Cost
Interviewer
How do you cancel?
You
I do not search the heap. I mark the job in the map and skip it when it reaches the top. The map is the truth.
Interviewer
And with two threads?
You
One lock around each public method, because the map and the heap must change together. A concurrent map alone would protect only half.
Interviewer
Would you do that for thirty jobs?
You
No. With thirty I keep the map and take the minimum with a loop. One container, no invariant to break.
Summary
The whole topic in one minute.
List the calls, name the question of each, and let the question pick: map for a key, sorted map for a range, heap for the smallest, deque for first in first out, stack for last in first out, bit set for many flags, linked map for order plus lookup.
Two fast questions mean two containers, one place that changes both, and an invariant you can say aloud.
The lock follows from the calls as well: an atomic for one counter, a lock for check then act, a semaphore for a limit plus a container for which one, a read-write lock only when long reads are common and a read changes nothing.
- Call, question, container, cost, size.
- A small list is a real answer. Give the number.
- Two fast questions: two containers, one owner, one invariant.
- Heap and cancel: mark in the map, skip at the top.
- A semaphore counts. It does not choose.
- If a read changes something, a read-write lock does not help.
- Never give the container away. Give answers.