Put a ring on it.
Implement RingBuffer, a fixed-capacity ring buffer for events. The buffer stores events in insertion order and automatically drops the oldest event when full.
This problem focuses on stateful component behavior and clear policy enforcement rather than algorithmic tricks.
Constructor
RingBuffer(capacity)
- Initializes an empty buffer with a maximum capacity of
capacity. capacityis guaranteed to be a positive integer.
Methods
push(event)
- Event is a
stringtype. - Inserts a new event into the buffer.
- If the buffer is already full, the oldest event is dropped before inserting the new one.
- This operation produces no output.
- Print
null.
- Print
snapshot()
- Returns all events currently stored in the buffer in oldest → newest order.
- The returned events should be consecutive and space-separated when output.
- Calling
snapshot()must not modify the internal state of the buffer. - If the buffer is empty, print nothing (an empty line).
Notes
- You may assume single-threaded usage.
- The internal storage representation is up to you.
Examples
Example 1
Input:
RingBuffer 2
push a
push b
push c
snapshotOutput:
null
null
null
b cAccepted 5/31
Acceptance 16%
Loading editor...
Sample Input:
RingBuffer 3
push 1
push 2
snapshotExpected Output:
null
null
1 2