Read the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.
Available in Python and C++. You are solving it in Python. Switch to C++
Implement a class RingBuffer(capacity), a fixed-capacity first-in first-out
queue built with head and tail index arithmetic.
A fixed-size queue sits at the thread boundaries of a trading system: between the feed handler and the strategy, and between the strategy and the order gateway. Production versions are ring buffers over pre-allocated memory. Here you build the single-threaded core.
It is backed by a single Python list of fixed length capacity, allocated
once in the constructor. You may not use collections.deque (or anything
from queue); the point is the wrap-around bookkeeping.
enqueue(item): append at the back and report success, or report failure
if the buffer is full (the buffer is unchanged).dequeue(): remove and return the oldest item, or report that the buffer
is empty.peek(): return the oldest item without removing it, or report that the
buffer is empty.size(): return the number of items currently held.In Python enqueue returns True on success and False on a full buffer,
and an empty buffer is reported as None.
class RingBuffer:
def __init__(self, capacity: int) -> None: ...
def enqueue(self, item: int) -> bool: ...
def dequeue(self) -> int | None: ...
def peek(self) -> int | None: ...
def size(self) -> int: ...
The tests drive your class through the run_ops(capacity, ops) driver
already in the scaffold (do not modify it): ops are ("enqueue", x),
("dequeue",), ("peek",) and ("size",), one recorded output per op.
run_ops(2, [("enqueue", 7), ("enqueue", 8), ("enqueue", 9), ("size",), ("peek",), ("dequeue",), ("dequeue",), ("dequeue",)])
# [True, True, False, 2, 7, 7, 8, None]
# the third enqueue is rejected: capacity 2, and FIFO order is preserved
run_ops(3, [("dequeue",), ("peek",), ("enqueue", 1), ("dequeue",), ("enqueue", 2), ("size",), ("peek",)])
# [None, None, True, 1, True, 1, 2]
# dequeue and peek on an empty buffer return None
1 <= capacity <= 30000.None or booleans in the outputs).pop(0) shifts every element on each
dequeue; the fixed-length backing list with indices never moves an
element.