← All Exercises
Ring Buffer with Overwrite Reporting
basicjavascript
Background
Ring buffers back audio pipelines, serial port drivers, and bounded event queues because they recycle memory without allocation and never block the producer.
Problem
Implement a circular buffer of the given capacity. push appends a value; when the buffer is full it overwrites the oldest value and records it. pop removes and returns the oldest value, or null when empty. Output the sequence of popped values and the overwritten values in order.
Input
A JSON object {"capacity": number, "ops": [{"op":"push","v":any} | {"op":"pop"}]}.Output
A JSON object {"popped": any[], "overwritten": any[]} where pop on empty yields null.Sample tests
Sample 1
Input: {"capacity":3,"ops":[{"op":"push","v":1},{"op":"push","v":2},{"op":"push","v":3},{"op":"push","v":4},{"op":"pop"},{"op":"push","v":5},{"op":"pop"},{"op":"pop"},{"op":"pop"},{"op":"pop"}]}Expected: {"popped":[2,3,4,5,null],"overwritten":[1]}Sample 2
Input: {"capacity":2,"ops":[{"op":"push","v":"a"},{"op":"pop"},{"op":"push","v":"b"},{"op":"push","v":"c"},{"op":"push","v":"d"}]}Expected: {"popped":["a"],"overwritten":["b"]}Your solution
Learning objective
Practice modular index arithmetic for bounded queues and overwrite semantics.