Editor

Ring Buffer

#96 · Stacks and queues · Intermediate · 75 XP · about 15 min

A ring buffer keeps the most recent items in a fixed amount of space, like a sensor that remembers only its last few readings. Build a class RingBuffer(capacity):

  • put(item) adds item at the back. If the buffer is already full, the oldest item is dropped to make room and put returns it; otherwise put returns None.
  • get() removes and returns the oldest item, or returns None when the buffer is empty.
  • items() returns a list of the stored items, oldest first.
  • is_full() returns True when the buffer holds capacity items.
  • len(buffer) gives the number of stored items (write __len__).

The heart of the exercise: store the items in one list of length capacity, made in __init__ and never resized, together with the position of the oldest item and a count. A ring buffer never shifts items along when one leaves.

Examples

b = RingBuffer(3)
b.put(1)
b.put(2)
b.put(3)
b.is_full()  # returns True
b.put(4)     # returns 1
b.items()    # returns [2, 3, 4]
b.get()      # returns 2
len(b)       # returns 2

When 4 arrives the buffer already holds 1, 2 and 3, so the oldest item, 1, is dropped and returned.

Constraints

  • 1 <= capacity <= 10,000
  • Up to 100,000 calls in total, and items are never None.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.