8/28
Part 2 of 6 · Filling a rowLearn and do

One index walks the row once

fill_row starts each slot's scan at the front of the row. That repeats work: a title that was on the screen when slot 0 looked at it is still on the screen for slot 1. Under the screen rule nothing ever leaves shown, so a blocked title stays blocked.

So keep one index that only moves forward:

head, i = [], 0
while len(head) < width and i < len(row):
    title = row[i]
    i += 1
    if title not in shown:
        head.append(title)
        shown.add(title)

Every title is looked at once at most. A row of length L costs O(L), not O(width × L).

Checks against shown, for a row of 200 titles whose first 150 are on the screen, width 40
rescan per slot
6,820
one index
190

The rescan looks at the same 150 blocked titles for every one of the 40 slots. The single index passes them once.

Keep this trick in mind for later. It leans on one fact, that blocked stays blocked, and the grid rule in part 4 breaks that fact.

In the editor, write fill_row_fast(row, width, shown): the same result as fill_row, checking each title against shown at most once. The tests count the checks.