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

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

clerkcallerdeskRepairDeskby_numberMap: the truth1 radio9002 lamp8303 chair845by_timeHeap: suggestsentry 1830, job 2entry 2845, job 3entry 3900, job 1

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

thread AThreadhas7thread BThreadhasnonecounterCountervalue7read7

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

    critical

    The heap has already used the old value for its order.

    Wrong
    job.promised = 840          # heap holds job
    Right
    job.promised = 840heapq.heappush(heap, (840, job.number))
  • Handing out the container

    major

    A caller sorts or clears it, and your invariant is gone.

    Wrong
    def jobs(self):    return self._by_number
    Right
    def jobs(self):    return list(self._by_number.values())
  • Check and act apart

    critical

    Another thread comes in between.

    Wrong
    if key not in shared:    shared[key] = make()
    Right
    with lock:    if key not in shared:        shared[key] = make()
  • Semaphore without a container

    critical

    The count is right and two users sit on one bench.

    Wrong
    slots.acquire()bench = free[0]
    Right
    slots.acquire()with lock:    bench = heapq.heappop(free)
  • List as a queue

    minor

    Removing the first item moves all others.

    Wrong
    first = line.pop(0)
    Right
    line = 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.