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 C++. Switch to Python
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 std::vector<long long> of fixed length, sized once in
the constructor. std::deque and std::queue are not allowed; 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 C++ enqueue returns true on success and false on a full buffer, and
an empty buffer is reported as std::nullopt.
class RingBuffer {
public:
explicit RingBuffer(std::size_t capacity);
bool enqueue(long long item);
std::optional<long long> dequeue();
std::optional<long long> peek() const;
std::size_t size() const;
};
The tests drive your class through the run_ops(capacity, ops) driver
already in the scaffold (do not modify it). Each op is {"enqueue", x},
{"dequeue"}, {"peek"} or {"size"}, and the driver records one
std::optional<long long> per op: 1 or 0 for an enqueue, the item or
std::nullopt for a dequeue or peek, the count for a size.
RingBuffer ring(2);
ring.enqueue(7); // true
ring.enqueue(8); // true
ring.enqueue(9); // false, capacity 2, and the buffer is unchanged
ring.size(); // 2
ring.peek(); // 7
ring.dequeue(); // 7
ring.dequeue(); // 8, so FIFO order is preserved
ring.dequeue(); // std::nullopt
RingBuffer other(3);
other.dequeue(); // std::nullopt, dequeue and peek on an empty buffer
other.peek(); // std::nullopt
other.enqueue(1); // true
other.dequeue(); // 1
other.enqueue(2); // true
other.size(); // 1
other.peek(); // 2
1 <= capacity <= 30000.long long values.