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.
A fixed-size queue sits at every thread boundary of a trading system: between the feed handler and the strategy, between the strategy and the order gateway. The production versions are ring buffers over pre-allocated memory, and interviewers like to see you build the single-threaded core without a library doing the index arithmetic for you.
Implement a class RingBuffer(capacity) backed by a single Python list of
fixed length capacity, allocated once in the constructor, with head/tail
index arithmetic. You may not use collections.deque (or anything from
queue); the point of the exercise is the wrap-around bookkeeping.
enqueue(item): append at the back; return True, or False if the
buffer is full (the buffer is unchanged).dequeue(): remove and return the oldest item, or None if empty.peek(): return the oldest item without removing it, or None if empty.size(): return the number of items currently held.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; up to \(2 \times 10^5\) operations; items are
integers (which are never confused with 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.Run your code to check it against the sample tests. Results appear here.