AlgoViz

Data structures for LLD

medium 45 min

Inside 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

0:00 / 4:56

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

  1. 1953

    Hans Peter Luhn writes an internal IBM memorandum that uses hashing with chaining, the idea behind today's hash maps.

  2. 1962 or 1963

    Edsger Dijkstra invents the semaphore while working on an operating system for the Electrologica X8.

  3. 1964

    J. W. J. Williams introduces heapsort, and with it the binary heap as a structure of its own.

  4. 1970

    Rudolf Bayer and Edward McCreight present the B-tree, the ordered structure behind most database indexes.

  5. 1974

    Raphael Finkel and J. L. Bentley name the quadtree, a tree for points in two dimensions.

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

Step 1 of 4

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.

Noor's shed

Pile, hooks, rack, pyramid, row, pegs. Each answers one question well.

Step 1

From question to container

What do you need to ask?

I needContainerCostCareful
Instant lookup by idHash mapO(1) on averageNo order. Keys must not change while inside
Items in a range, next larger, previousSorted map (TreeMap, sorted list)O(log n) to find, then k for k resultsOne dimension only
Points within 5 milesGrid of cells, quadtree, or a spatial indexDepends on how points are spreadA sorted map of latitudes alone is not enough
Highest or lowest priority firstHeapO(1) to look, O(log n) to add or takeNot searchable, not fully sorted
True or false for very many itemsBit set1 bit each, O(1) by numberFinding a free one scans words, 64 bits at a time
Lookup and order of insertionLinked hash mapO(1)Java keeps insertion order, or access order if asked
Last in first out, first in first outStack, queue (a deque does both)O(1) at the endsA Python list is slow at the front
Is it there already?Hash setO(1) on averageNeeds equality that fits
Newest k of many sorted listsHeap of list heads (k-way merge)O(log k) for each resultHolds one entry per list
n is the number of items, k the number of results or lists.

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?

ItemsScan a listHeap or sorted map: about log2 nHash map
30up to 30about 5about 1
1,000up to 1,000about 10about 1
100,000up to 100,000about 17about 1
1,000,000up to 1,000,000about 20about 1
For 30 items nobody feels the difference. For 100,000 items and 50 calls a second, the scan looks at up to 5 million items each second.

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

CallHow oftenQuestionContainer
find(number)oftenby idMap from number to Job
next_urgent()oftensmallest promised timeHeap of (time, number)
cancel(number)sometimesby id, inside a heapMap, and lazy deletion in the heap
join(bench), call(bench)oftenorder of arrivalOne deque per bench

One list for everything

RepairDesk+ jobs: List<Job>+ find(number): Job+ nextUrgent(): Job+ cancel(number)Job+ number: int+ promised: Time+ cancelled: bool

1/3It works

A desk with a list. Each method walks through it. With twenty jobs that is fine.

has (lives on)uses

A container is private. Give out answers, not the container.

Three private containers, one owner

the truthRepairDesk+ find(number): Job+ nextUrgent(): Job+ cancel(number)+ join(bench, name)Map<int, Job>get O(1)Job- number: int- promised: Time- open: bool

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)

The owner is the only writer. That is what makes two containers safe.

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 = 1

Lines 6 to 11

The job knows whether it is open. The heap does not need to know, and that keeps cancel cheap.

1 of 3

Pairs

Composite structures you will meet again

Two containers, one job

PairGives youUsed in
Hash map and doubly linked listLookup and move to front, both O(1)LRU cache
Hash map and heapLookup and smallest, cancel by lazy deletionJob scheduler, timers
Hash map and sorted setLookup and ranking or rangeLeaderboards, auction
Map of dequesOne line per groupWaiting lists, pub and sub
2D array and stackSquare by position, undo of the last moveChess
Bit set and mapFirst free number, who holds itParking lot
Array used as a ringLast N items without allocationLogger

One call updates both

The map is the truth. The heap only suggests.

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

ToolUse it forTrap
Read-write lockOne writer, many readers, for example a catalogue. Many may read togetherWorth it only for long or frequent reads. An LRU read moves an entry, so it is a write
SemaphoreA limited number, for example 50 parking spots or a connection poolCounts permits. It does not say which spot, so you still need a safe container
Atomic integerA simple counter or a request id, without a lockTwo atomics together are not atomic. For hot statistics Java has LongAdder
synchronized, a lock, or a transactionSeveral steps that must happen as one, for example a money transfer or check then actA lock lives in one process. With two servers the database must decide
Blocking queueWork from one thread to anotherWithout a bound it grows until memory is gone
Thread localData of one thread, for example a log contextIn a thread pool it must be cleared, because threads are reused
The first four are the classic choice. The last two complete it.

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

how manyBenchPool+ take(): int+ give(bench)Semaphorepermits: 3acquire()release()

1/3How many

The semaphore lets three threads in and makes the fourth wait.

owns (dies together)

Semaphore alone: correct count, two people at the same bench.

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.

1 of 4

Two threads, one free bench, no lock

Check then act. The lock must cover both lines. More in correctness under concurrency.

Classic problems

Which container in which problem

ProblemHot callContainer and lockWhy
Elevatornext stop above meSorted set of floors for each directionA heap gives the smallest, not the next above
Parking lotnearest free spotHeap or bit set per size, map by ticket, one lockTake must be check and act
LRU cacheget and move to frontHash map and linked list, one lockReads change the order
Movie bookinghold these seatsMap by seat, expiry heap, lock per showAll seats or none
Meeting scheduleroverlap with a timeSorted map by startLook at the one before and the one after
Feednewest 20 of 300 peopleHeap of 300 heads20 results cost about 20 times log 300
Loggerappend, never wait longBounded queue or ring buffer, one writerThe file is slow
Rate limiterhow many in the last minuteDeque of times per userOld 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?

  1. Interviewer

    You wrote a heap. Why?

  2. 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
  3. Interviewer

    How do you cancel?

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

  5. Interviewer

    And with two threads?

  6. You

    One lock around each public method, because the map and the heap must change together. A concurrent map alone would protect only half.

  7. Interviewer

    Would you do that for thirty jobs?

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

Sources