7/30
Part 2 of 7 · One loop at a timeLearn and do

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.