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
See it run
Each container answers one question. Watch two of them stay in step.
Operations
Map and heap in step
Three jobs, one cancelled, one moved. The heap keeps old entries and the map exposes them.
Step 1 of 6
Three jobs
Both containers know them. Times are 830, 845 and 900.
Step 1: Three jobs
def move(self, number, promised): self._by_number[number].promised = promised heapq.heappush(self._by_time, (promised, number))def cancel(self, number): self._by_number[number].open = Falsedef next_urgent(self): while self._by_time: promised, number = heapq.heappop(self._by_time) job = self._by_number[number] if job.open and job.promised == promised: job.open = False return job- Question
- id, smallest
- Cost
- O(1), O(log n)
The map is the truth. The heap only suggests.
In the real world
The same data structures for lld doing real jobs. Pick one and step through it.
Two threads add one to the same number.
Step 1 of 4
A reads 7
Adding is read, add, write.
Step 1: A reads 7
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Changing a value inside a heap
criticalThe heap has already used the old value for its order.
Wrongjob.promised = 840 # heap holds jobRightjob.promised = 840heapq.heappush(heap, (840, job.number))Handing out the container
majorA caller sorts or clears it, and your invariant is gone.
Wrongdef jobs(self): return self._by_numberRightdef jobs(self): return list(self._by_number.values())Check and act apart
criticalAnother thread comes in between.
Wrongif key not in shared: shared[key] = make()Rightwith lock: if key not in shared: shared[key] = make()Semaphore without a container
criticalThe count is right and two users sit on one bench.
Wrongslots.acquire()bench = free[0]Rightslots.acquire()with lock: bench = heapq.heappop(free)List as a queue
minorRemoving the first item moves all others.
Wrongfirst = line.pop(0)Rightline = deque()first = line.popleft()
Interview tips
Four words
- Call.
- Question.
- Container.
- Size.
Pairs
- One owner.
- One method.
- One invariant, said aloud.
Locks
- Count: atomic.
- Check then act: lock.
- Limit: semaphore and container.
Small is fine
- Thirty items: a loop.
- Say when it changes.