Library/Coding patterns that get asked/Rotate and dedupe what users see

Rotate titles by score, with no repeats

100 min7 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Sort titles by score with an exact tie-break, and say why reverse=True flips the tie-break too
  • Rotate through a catalog one call at a time, and say why a cursor breaks once scores change
  • Keep two sorted lists, waiting and shown, and move a title's key inside the list that holds it when its score changes
  • Say what a heap costs here: lazy deletes, stale keys that pile up, and measured update times against sorted lists
  • Stop a title from showing twice in a row across loops, then generalize it to a cooldown of k calls
  • Answer the follow-ups: where the locks go, storing scores in a Redis sorted set, and many viewers on one ranking
Part 1 of 7about 15 min
Score order

Movie billboard rotation

Netflix software engineer candidates report this coding round, in an onsite (1 report) and in a data platform loop, where the candidate called it a known question from other reports (1 report). A prep site lists a version of it for ML engineers too (1 source). It starts like this:

The home page has one billboard, and it shows one title at a time. You get the catalog as a dict from title to score. Write a class Billboard(scores) with a method get() that returns the next title to show. Show the best score first. Every title shows once before any title shows again, and then the loop starts over. Break a tie by title, in alphabetical order. With no titles, return None.

Catalogget(), called seven times
{"Orbit": 5, "Maple": 7, "Comet": 9, "Tundra": 3, "Harbor": 7}Comet, Harbor, Maple, Orbit, Tundra, Comet, Harbor
{}None every time

Then the scores change while the billboard runs. update(title, score) has to count at once, and a title already shown in this loop waits for the next one (1 report). After that comes the rule the prep site's version names: no immediate repeats (1 source). An update can make the last title of one loop the best one of the next, and the billboard must not show it twice in a row. The last level stretches that into a cooldown of k calls.

You don't write it yet. The lesson first teaches the pieces: a sort with an exact tie-break, a loop that keeps its place, two sorted lists that survive updates, and why a heap makes updates hard. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.

This lesson builds on sorting with tie-breaks, from the database lesson, and on the heaps lesson: the billboard is a ranking that has to keep changing while it runs.

Sort by score, highest first, and settle ties by title

The catalog in every example of this lesson is the one from the prompt:

CATALOG = {"Orbit": 5, "Maple": 7, "Comet": 9, "Tundra": 3, "Harbor": 7}
print(sorted(CATALOG, key=lambda title: CATALOG[title], reverse=True))
Predict

Maple and Harbor both have 7. Which one does this sort put first?

Pick one to see what it prints.
Pick an answer above to see the rest

reverse=True reverses the tie-break too

The first fix most people try keeps reverse=True and adds the title to the key:

print(sorted(CATALOG, key=lambda title: (CATALOG[title], title), reverse=True))
['Comet', 'Maple', 'Harbor', 'Orbit', 'Tundra']

Maple still comes before Harbor, and now for a different reason. reverse=True reverses the whole comparison, the title included, so ties come out in reverse alphabetical order. It passes every test without a tie and fails the first one with a tie.

There's a second correct way, and it explains why the sort is built the way it is. Python's sorting guide says the reverse parameter still maintains sort stability: equal keys keep their order. So you can sort twice. First sort by the tie-break, then sort by score with reverse=True. The second sort decides the order, and wherever two scores are equal, the stable sort keeps the alphabetical order the first pass left.

titles = sorted(CATALOG)
titles.sort(key=lambda title: CATALOG[title], reverse=True)
print(titles)
['Comet', 'Harbor', 'Maple', 'Orbit', 'Tundra']

The rule to remember: the last sort is the main order, and each earlier sort only settles ties. Two passes help when one key can't express both orders, such as a descending string after an ascending number.

The editor holds a rank that sorts twice, with the two passes in the wrong order. Run it on the tie it prints, then fix rank by swapping the passes.

Store the key, not the title

From here on, the lesson stores keys instead of bare titles. A key is the tuple (-score, title):

keys = sorted((-score, title) for title, score in CATALOG.items())
print(keys)
print(min(keys))
[(-9, 'Comet'), (-7, 'Harbor'), (-7, 'Maple'), (-5, 'Orbit'), (-3, 'Tundra')]
(-9, 'Comet')

Three things make keys better than titles:

  • A key sorts without the dict. sorted(keys) needs no key= function, because the tuple already holds everything the order depends on. Sorted lists and heaps compare keys directly, and both come later in this lesson.
  • The smallest key is the best title. min(keys) is the title to show next, and keys[0] is the same thing once the list is sorted.
  • No two keys are ever equal. Titles are unique, so the title ends every tie. Python's heapq notes warn that a tuple compare breaks when two priorities are equal and the items after them can't be compared. Here the item after the score is a string, which always compares.

The cost of a key is that it goes stale. When a score changes, the old key is still sitting in whatever list holds it. Part 3 is about exactly that.

The editor holds key and best. Write key(title, score) to build the tuple, and best(scores) to return the title whose key is smallest.

Watch · 4 min

Python's key parameter, first with abs from 6:21, then on a list of employee objects that won't sort without one from 7:26, and reverse=True next to a key at 9:34. He sorts on one attribute at a time. This part's key is a tuple, so a tie on the score falls to the title, and reverse=True would flip that tie-break too.

Python Tutorial: Sorting Lists, Tuples, and Objects · Corey Schafer · Dec 2015YouTube
Part 1 done
Part 2 of 7about 11 min
One loop at a time

A loop shows each title once, then starts again

Level 1 is a round robin: walk the sorted titles from the top, and when you pass the end, start again at the top. All it needs is a position, called a cursor, that moves one step per call and wraps around with %:

order = ["Comet", "Harbor", "Maple"]
cursor = 0
shown = []
for _ in range(5):
    shown.append(order[cursor])
    cursor = (cursor + 1) % len(order)
print(shown)
['Comet', 'Harbor', 'Maple', 'Comet', 'Harbor']

(cursor + 1) % len(order) counts 0, 1, 2, 0, 1. The % gives the remainder after dividing, so the step after the last index lands back on 0.

Read before you move. If the cursor moves first, the first call shows the second title, and the best title waits a whole loop.

An empty catalog breaks the modulo: % 0 raises ZeroDivisionError. The prompt says an empty billboard returns None, so check for it before you divide.

The editor holds rotation with its cursor set up. Write rotation(order, n) so it returns the first n titles shown, going round order again and again.

A class keeps its place between calls

The interviewer doesn't call a function once with n. They call get() again and again, and each call has to remember where the last one stopped. That memory lives on the object.

Two attributes are enough for level 1:

  • self.order, the titles in billboard order, sorted once in __init__
  • self.cursor, the index of the next title to show

Sorting once costs O(n log n) for n titles. After that, each get is O(1): read one index, move the cursor.

Set both attributes in __init__. An attribute written in the class body, outside any method, is shared by every instance, so two billboards built from the same catalog would share one cursor and steal each other's turns.

CallCursor beforeShowsCursor after
10Comet1
21Harbor2
54Tundra0
60Comet1

The editor holds Board, level 1 of the billboard built on a cursor. Write __init__ to store self.order and self.cursor, and get to return the next title.

An update breaks the cursor

Level 2 lets scores change between calls. Here's the cursor version after Comet and Harbor have shown, when Tundra's score jumps to 10 and the order is sorted again:

scores = dict(CATALOG, Tundra=10)
order = sorted(scores, key=lambda title: (-scores[title], title))
cursor = 2
print(order)
print(order[cursor:])
Predict

Comet and Harbor have shown, so the cursor is 2. Tundra rises to 10 and the list is sorted again. Which title does the cursor show next?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 2 done
Part 3 of 7about 16 min
Two sorted lists

Keep two sorted lists: waiting and shown

The candidate who reported the movie playlist rotated through the titles with two sorted lists, and another candidate's advice was two sorted maps (2 reports). Here's the idea. Split the keys by whether their title has shown in this loop:

  • waiting: keys of titles not yet shown, sorted, so waiting[0] is the next title.
  • shown: keys of titles already shown in this loop, also sorted.

get takes waiting[0], files it into shown, and returns its title. When waiting runs out, the loop is over: every key is in shown, already in order, so it becomes the new waiting, and shown starts empty.

After callwaitingshown
0Comet, Harbor, Maple, Orbit, Tundra
2Maple, Orbit, TundraComet, Harbor
5Comet, Harbor, Maple, Orbit, Tundra
6Harbor, Maple, Orbit, TundraComet

The two lists answer the question the cursor couldn't. A title is shown if its key is in shown, whatever its score does next.

Inside a class, the refill is a swap: self.waiting, self.shown = self.shown, [], which is O(1). In a plain function that gets the two lists as arguments, you can't rebind the caller's names, so refill in place with waiting.extend(shown) and shown.clear().

waiting.pop(0) shifts every key left, so it costs O(n). That's fine at catalog sizes, and the next step measures it. A sorted container from a library, like Java's TreeMap, does it in O(log n).

The editor holds get(waiting, shown) as a plain function over the two lists. Write it: show the best waiting key, file it into shown, and refill waiting when it runs out.

bisect.insort files a key in its place

A list stays sorted only if every key goes in at the right spot. The bisect module finds that spot by binary search:

from bisect import bisect_left, insort

WAITING = [(-9, "Comet"), (-7, "Harbor"), (-7, "Maple"), (-5, "Orbit"), (-3, "Tundra")]
print(bisect_left(WAITING, (-7, "Maple")))
print(bisect_left(WAITING, (-8, "Maple")))
2
1

bisect_left(keys, key) returns the index where key would go to keep the list sorted. If the key is in the list, that's its index: (-7, 'Maple') is at 2. If it isn't, you still get a number. (-8, 'Maple') would go at 1, where Harbor sits. So after bisect_left, check keys[i] == key before you trust the index, and check i < len(keys) first, because a key past the end gives len(keys).

insort(keys, key) does the search and then inserts. The search is O(log n), and the insert shifts every later key one place, which is O(n). The bisect docs say plainly that the slow insertion step dominates. In practice the shift is a fast memory copy in C: at 100,000 titles, a delete plus an insert measured about 20 µs.

The editor holds add and find over a sorted list of keys. Write add(keys, title, score) with insort, and find(keys, title, score) with bisect_left, returning -1 when the key isn't there.

An update moves a key inside the list that holds it

Now level 2. update(title, score) has three cases:

The title isWhat happens to its key
waitingmoves inside waiting, so it shows in this loop by its new score
shownmoves inside shown, so it waits for the next loop
newgoes into waiting, so it shows in this loop

The steps for a known title, in this order:

  1. Build the old key from the score you have stored: (-scores[title], title).
  2. Look for it in waiting with bisect_left. If it isn't there, it's in shown.
  3. Delete it from that list.
  4. Store the new score, and insort the new key into the same list.

You need the dict of scores for step 1. A key is found by its exact value, and the list doesn't know a title's score unless you kept it somewhere. In the class, that dict is self.scores, and __init__ should store a copy, self.scores = dict(scores). The caller's dict belongs to the caller: the practice problem's tests check that an update leaves it alone. Each update is two binary searches, one delete and one insert: O(log n) to find, O(n) to shift.

Why does a new title wait in the current loop? Because it hasn't been shown in it. That holds even when every other title has already shown. The new title goes into waiting, so the next get shows it before the loop turns over.

The editor holds update over the dict and the two lists. Write update(scores, waiting, shown, title, score) to cover all three cases.

Find the bug: a title that shows twice in one loop

This one looks right, and it passes a test where every title is new. Then a score changes and a title shows twice.

The order of two lines decides it. The old key is built from scores[title]. Overwrite the score first and the "old" key is really the new key. The search doesn't find it, nothing is deleted, and the real old key stays in its list next to the new one. Now the title is in the billboard twice, and get will show both.

A test with a known title catches it. So does printing the lists after one update and counting the keys. Five titles should mean five keys.

The editor holds an update with one line in the wrong place. Run it, read waiting in what it prints, and move the line in update so the old key is removed.

Part 3 done
Part 4 of 7about 15 min
Why not a heap

A heap pops the best key in O(log n)

A heap is the usual tool for "always take the best", and it's where many people start. One candidate who reported the movie playlist tried a heap first and got stuck on it for a long time, then switched to sorted lists. Another's advice was to skip the heap (2 reports). It helps to see where it works and where it stops.

For level 1 alone, a heap is fine. heapq.heapify turns the list of keys into a heap in O(n). Each heappop returns the smallest key in O(log n), so a loop pops the keys in billboard order:

import heapq

heap = [(-score, title) for title, score in CATALOG.items()]
heapq.heapify(heap)
print(heap[0])
print(heap)
(-9, 'Comet')
[(-9, 'Comet'), (-7, 'Harbor'), (-5, 'Orbit'), (-3, 'Tundra'), (-7, 'Maple')]

Only heap[0] has a known place. The rest of the list isn't sorted: Maple sits last even though it's the third best. So you never read a heap's list in order. You pop it.

To start the next loop, keep the popped keys and heapify them again, or keep a second heap for the shown titles. Either is O(n) per loop or O(log n) per call.

The editor holds one_loop. Write one_loop(scores): heapify a key per title, then pop every key and return the titles in the order they came out.

A heap can't find a title, so an update pushes a second key

The trouble starts at level 2. To change Harbor's score, you'd remove its old key and add a new one. A heap can't find (-7, 'Harbor') without scanning the whole list, O(n). And deleting from the middle of a heap breaks its order unless you repair it by hand.

The usual way out is a lazy delete. Leave the old key where it is and push a new one. Keep the current score of each title in a dict. When a key reaches the top, check it:

  • If its score isn't the title's current score, it's stale. Drop it and pop again.
  • If its title has already shown in this loop, drop it too.
  • Otherwise, show it.
scores = {"Comet": 9, "Harbor": 7, "Orbit": 5}
heap = [(-9, "Comet"), (-7, "Harbor"), (-5, "Orbit")]
scores["Comet"] = 1
heapq.heappush(heap, (-1, "Comet"))
print(sorted(heap))
[(-9, 'Comet'), (-7, 'Harbor'), (-5, 'Orbit'), (-1, 'Comet')]

Comet has two keys now. The one with 9 will reach the top first, and only the check against scores stops Comet from showing as if it were still the best title.

Each loop of pop_best pops one key, so it always ends: at worst the heap runs out and it returns None.

The editor holds pop_best and a heap with one stale key. Write pop_best(heap, scores, shown) to pop keys until one is current and not yet shown.

Stale keys pile up, and sorted lists stay small

Every update leaves one stale key behind. After a million updates on a catalog of 1,000 titles, the heap holds about a million keys, and nearly all of them are dead. The fix is to rebuild now and then: when stale keys outnumber live ones, throw the heap away and heapify a fresh one from the scores dict, in O(n).

Here's what one update cost, measured in Python 3.12 with random scores. Each number is microseconds per update, best of 3 runs:

Per update1,000 titles10,000100,000
heap: push a second key0.59 µs0.89 µs1.04 µs
two sorted lists: find, delete, insort1.24 µs3.16 µs20.10 µs
scan every title for the best (one get)71.53 µs625.73 µs6,538.52 µs
sort the whole catalog again189.04 µs2,822.85 µs56,572.44 µs
One update or get at 100,000 titles, log scale
heap push
1.04 µs
sorted lists
20.1 µs
scan
6,539 µs
sort again
56,572 µs

The heap's push is fastest, but it's only half the work. It moves the cost into get, which pops stale keys, and into the rebuilds. The sorted lists pay a little more per update and never hold a dead key, so get stays one pop. Both beat re-sorting by a factor of thousands.

So why do candidates steer away from the heap? Not speed. It's the bookkeeping: a scores dict to spot stale keys, a shown set, a rebuild rule, and a second heap or a rebuild at every loop. Two sorted lists need none of that. In Java, a TreeMap or TreeSet gives O(log n) for every step. Python has no sorted container built in, and bisect on a list is the plain substitute.

The editor holds compact and stale. Write compact(heap, scores) to rebuild a fresh heap with one key per title, and stale(heap, scores) to count the dead keys.

Watch · 2 min

A max heap from 11:21, then tuples on a heap from 11:55, with the priority first so the heap orders by it. Python's heapq only pops the smallest, which is why this part's keys start with the negated score.

Heaps & Priority Queues - Heapify, Heap Sort, Heapq Library - DSA Course in Python Lecture 9 · Greg Hogg · Jul 2024YouTube
Part 4 done
Part 5 of 7about 13 min
No repeats

A repeat can only happen where two loops meet

Level 3 says no title twice in a row. Inside one loop that can't happen, because each title shows once per loop. The only place left is the seam, where the last title of one loop meets the first title of the next.

Without updates, the seam is safe too. The last title is the worst one and the first is the best, so they differ unless there's only one title. An update is what makes the seam dangerous. Here's the two-list billboard with no repeat rule. After Comet, Harbor, Maple and Orbit show, Tundra rises to 10:

CallShows
1 to 4Comet, Harbor, Maple, Orbit
updateTundra's score goes to 10
5Tundra
6Tundra
7Comet

Tundra was still waiting, so call 5 shows it, and that ends the loop. Call 6 starts a new loop, and Tundra, at 10, is now the best title of all. Two Tundras in a row.

This is the rule the prep site's version of the question names: avoid immediate repeats (1 source). Before you fix it, write the check that finds it. A check you can run on any output is how you'll test every level from here on.

The editor holds repeats. Write repeats(shows) to return each index where a title is the same as the one just before it.

Skip the title shown last, and keep it waiting

The fix: when the best waiting title is the one shown on the call just before, show the next best instead. The skipped title doesn't lose its turn. It stays in waiting, by its score, and since it's still the best there, it shows on the very next call.

Callwaiting beforeLast shownShows
6Tundra, Comet, Harbor, Maple, OrbitTundraComet
7Tundra, Harbor, Maple, OrbitCometTundra
8Harbor, Maple, OrbitTundraHarbor

So the run reads Comet, Harbor, Maple, Orbit, Tundra, Comet, Tundra, Harbor, Maple, Orbit. Every title still shows once per loop. Only the order inside the new loop changed.

Two details make the rule exact:

  • Compare titles, not keys. The key stored for the last title may hold an old score. The title doesn't change.
  • A lone title still shows. With one title in the catalog, no other title can take its place, so it shows every time. Without that case, get would have nothing to return.

The cost is small. At most one key is skipped, so get looks at two keys at most and stays O(1) beyond the pop.

The editor holds pick. Write pick(waiting, last) to return the index of the first key whose title isn't last, or 0 when no other title can show.

A cooldown of k: remember the call each title last showed

Level 4 stretches the rule: a title shown in any of the last k calls is cooling and can't show. Level 3 is k = 1, and k = 0 turns the rule off.

Remembering only the last title isn't enough any more. Count the calls instead, and keep a dict from each title to the number of the call that last showed it:

  • On call number now, a title that last showed at call m is cooling when now - m <= k.
  • A title that never showed isn't cooling.

Then get walks waiting from the front and shows the first key whose title isn't cooling. At most k titles can be cooling, so the walk skips at most k keys.

What if every title still waiting is cooling? That happens with a short catalog and a long cooldown. Show the one that showed longest ago, the smallest call number. That's the choice that keeps titles as far apart as the catalog allows.

Picking the best waiting title instead sounds simpler, and it backfires. Take three titles, A at 9, B at 5 and C at 1, with k = 3. One loop shows A, B, C, then C rises to 20. At call 4 all three are cooling. The best of them is C, which showed on call 3, the call just before. The longest ago is A:

FallbackCalls 1 to 6
show the one shown longest agoA, B, C, A, B, C
show the bestA, B, C, C, A, B

With "the best", a longer cooldown produces the very repeat that k = 1 prevents.

The editor holds cooling and pick. Write cooling(title, last_call, now, k) and pick(waiting, last_call, now, k), with the fallback to the title shown longest ago.

Watch · 11 min

LeetCode's Reorganize String, a cooldown of 1: no letter twice in a row. From 4:30 he takes the most frequent letter each time and puts the one he just used on hold, the same move as this part's skip of the title shown last. The code is from 8:17.

Reorganize String - Tesla Interview Question - Leetcode 767 - Python · NeetCode · Dec 2021YouTube
Part 5 done
Part 6 of 7about 13 min
The worked example

A worked example: spread out repeated letters

A classic interview problem uses the same cooldown with a heap: arrange letters so that no letter comes back within k places. Given {"a": 3, "b": 2, "c": 1} and k = 1, one answer is ababac.

The plan is greedy. At each place, take the letter with the most copies left, because the most common letter is the hardest to fit. A letter you just used can't come back for k places, so it waits in a queue until its return place.

  • heap: letters ready to use, as (-copies_left, letter), so the most copies pops first and ties go alphabetically.
  • cooling: letters waiting, as (return_place, -copies_left, letter).

Each place does three things: move back every letter whose return place has come, pop the best letter from the heap, and if it has copies left, put it in cooling until place + k + 1. Places come in order and every return place is the current place plus the same k + 1, so the queue is already sorted by return place. A plain list or a deque works, with no second heap.

If the heap is empty at some place, every letter left is cooling, and nothing can go there. Then no arrangement exists, and the answer is an empty string. {"a": 3, "b": 1} with k = 2 fails that way: after a and b, only a is left, and it showed one place ago.

Here's the billboard's cooldown with one difference: a billboard can always show something, using the fallback, and this problem can't, so it gives up.

The editor holds spread with its heap and queue set up. Write the body of the loop in spread(counts, k).

Count the places without building the schedule

A close cousin allows idle places. Tasks run one per place, a task can't run again within k places, and an idle place is allowed. How few places can every task fit in?

The most common task sets the frame. If A runs m times, its runs need k places between each pair, so the frame is (m - 1) * (k + 1) places, plus one for the last A. With A 3 times and k = 2:

Place1234567
TaskAAA

Every other task with the same count m adds one place at the end, after the last A. Everything else fills the gaps. So the frame is (m - 1) * (k + 1) + c, with c the number of tasks tied at m.

If there are more tasks than the frame has room for, nothing ever idles, and the answer is the total number of tasks. So the answer is the larger of the two.

The formula is easy to get wrong in two ways: forgetting c, and forgetting the total. A simulation in the tests checks it against a step-by-step schedule on 300 random cases.

The editor holds slots. Write slots(counts, k) with the formula.

Test the edges, then give the cost

The edges for a cooldown problem:

  • k = 0: no rule at all, so repeats are fine.
  • One letter: possible only if it appears once, or k is 0.
  • A letter that fills more than its share: impossible, and you return an empty string.
  • Ties in the counts: the tie-break decides the output, so say it.
  • Empty input: an empty string, and not an error.

A checker is worth more than any one of those tests. Write far_enough(s, k) once and run it on every output, including hundreds of random inputs. It also checks the billboard: for a run with no updates, two showings of a title must stand more than k calls apart, except where the fallback had no other choice.

The cost of spread: each place does one pop and at most one push on a heap of a distinct letters, so it's O(n log a) for n letters in all. slots is O(a). The billboard's cooldown is O(k) extra per get at most.

The editor holds far_enough. Write far_enough(s, k) so it returns True when every two equal letters in s stand more than k places apart.

Watch · 13 min

LeetCode's Task Scheduler, where a task waits n turns before it can run again. The idea from 4:05, a max heap of counts and a queue of tasks cooling down from 6:52, and the code from 11:45. It's this worked example's heap and queue, counting turns instead of placing letters.

Task Scheduler - Leetcode 621 - Python · NeetCode · Nov 2021YouTube
Part 6 done
Part 7 of 7about 17 min
Follow-ups

What interviewers ask next

The candidates report two follow-ups after the code (2 reports):

  • Multithreading. One candidate answered by saying out loud where the locks would go, and that part went fine (1 report).
  • Running it in production. How you'd scale it, and how you'd store and read the data (1 report).

Other natural ones are many viewers sharing one ranking, and what you'd test.

Where the locks go

get and update both read and change the two lists. Run them on two threads at once and an update can delete a key while get is moving it between lists, or both can pop the same key. So each whole call needs the lock, from the first read to the last write.

One lock for the billboard is the right first answer. A lock per list sounds finer, and it breaks: get changes both lists in one step, so it would need both locks, and two calls that take them in opposite orders can wait on each other forever. Say that, then say what you'd measure before splitting the lock: how long a call holds it. At about 20 µs per update, one lock serves tens of thousands of calls a second.

Use with self.lock:. It gives the lock back when the block ends, even when the call inside raises. An acquire and release pair without try and finally leaves the lock held after an error, and every later call waits forever.

The editor holds LockedBoard, which wraps any billboard, and OneTitle, a stand-in board that always shows Comet. Write get and update in LockedBoard so each runs inside self.lock.

In production, a sorted set holds the scores

The scores live in a shared store, not in one process's memory. Redis has a type made for this: the sorted set. Each member has a score, adding or changing one is O(log n), and you can read members in order by rank.

The order has the same trap as reverse=True. Redis's docs say members with the same score are ordered lexicographically, from A to Z. Read from highest score to lowest, with ZREVRANGE or ZRANGE with REV, and ties come out in descending lexicographical order, from Z to A. That's Maple before Harbor again.

The same fix works. Store each score negated and read with plain ZRANGE: the highest score comes first, and ties stay from A to Z.

The rest of the design follows from the two lists:

  • One sorted set holds the catalog's scores, shared by every server.
  • Each viewer's state is small: which titles they've seen this loop, or a cursor plus a version of the ranking.
  • Scores change through update calls from a scoring job. Writing the new score to the sorted set is the whole update.

The editor holds zrange, zrevrange and billboard. Write the first two the way Redis orders members, then billboard(scores) from zrange with negated scores.

Many viewers: share the ranking, keep a little state per viewer

Netflix doesn't show one billboard. Every viewer has their own rotation, and a viewer's loop has nothing to do with anyone else's. Building a Billboard per viewer copies the whole catalog per viewer, which is wasteful when the ranking is the same for everyone.

Split what's shared from what isn't:

  • Shared: the ranked order of titles, rebuilt when scores change.
  • Per viewer: the set of titles they've seen in their current loop.

The next title for a viewer is the first one in the shared order that isn't in their set. When every title in the order is in the set, the loop is over: clear the set and start again.

Check "every title is in the set" with the titles themselves, not with the sizes. A viewer's set can hold a title the catalog has since dropped. Then the set is as big as the catalog while a title is still unseen, and a size check starts a new loop too early.

Walking the order from the top is O(n) per call in the worst case. A per-viewer cursor into a versioned order is O(1), and when the version changes, you fall back to the set.

The editor holds next_for. Write next_for(order, seen) to return a viewer's next title, starting a new loop when every title in order is in seen.

The tests you'd write

One candidate ran out of time before writing any tests (1 report). Name them early, even if you only get to write a few:

  • Ties, with the dict holding them out of alphabetical order.
  • An empty catalog, one title, and two full loops.
  • An update to a waiting title, a shown title and a new title, including one added after every other title has shown.
  • The seam, and a cooldown longer than the catalog.
  • A property check on a run with no updates: each loop holds each title once, and nothing repeats in a row.

The editor holds loops_ok. Write loops_ok(shows, n), the property check from the last item above: every loop of n shows holds no title twice, and no title shows twice in a row.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
6 questions
  1. 1.The catalog is {Maple: 7, Harbor: 7, Comet: 9}. What does sorted(catalog, key=lambda t: (catalog[t], t), reverse=True) return?

  2. 2.Comet and Harbor have shown. Tundra rises from 3 to 10, and the billboard sorts its list again and keeps its cursor at 2. What goes wrong?

  3. 3.Comet has already shown in this loop. Its score drops from 9 to 1. Where does its new key go?

  4. 4.Why does a lazy-delete heap need the dict of current scores?

  5. 5.Three titles A, B and C showed in calls 1, 2 and 3, and the cooldown is 3. At call 4 every title is cooling. Which title shows?

  6. 6.Your billboard keeps scores in a Redis sorted set and reads them with ZRANGE ... REV. Maple and Harbor tie. Which comes first, and what's the fix?

Practice

Sources (5)
  1. Sorting Techniques · Python 3.12 documentation · Dec 1, 2026
    “The reverse parameter still maintains sort stability (so that records with equal keys retain the original order).”
  2. bisect: insort_left · Python 3.12 documentation · Oct 26, 2026
    “Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.”
  3. heapq: Priority Queue Implementation Notes · Python 3.12 documentation · Oct 26, 2026
    “Tuple comparison breaks for (priority, task) pairs if the priorities are equal and the tasks do not have a default comparison order.”
  4. ZRANGE · Redis documentation · Dec 1, 2026
    “Elements with the same score are ordered lexicographically.”
  5. ZREVRANGE · Redis documentation · Dec 1, 2026
    “Descending lexicographical order is used for elements with equal score.”