Circular Buffer - Problem
A circular buffer is a fixed-size data structure that uses a single, fixed-size buffer as if it were connected end-to-end. This structure is useful for buffering data streams where the oldest data is automatically overwritten when the buffer is full.
Implement a CircularBuffer class with the following operations:
- add(value): Add an element to the buffer. If the buffer is full, overwrite the oldest element.
- read(): Read and remove the oldest element from the buffer. Return
nullif the buffer is empty.
Your implementation should handle the buffer's full and empty states correctly and use modulo arithmetic for efficient wraparound.
Input & Output
Example 1 — Basic Operations
$
Input:
capacity = 3, operations = [["add",1],["add",2],["read"],["add",3],["add",4],["read"],["read"]]
›
Output:
[1,2,3]
💡 Note:
Add 1,2 → buffer=[1,2,null]. Read returns 1 → buffer=[null,2,null]. Add 3,4 → buffer=[4,2,3] (4 overwrites position 0). Read returns 2, then 3.
Example 2 — Empty Buffer
$
Input:
capacity = 2, operations = [["read"],["add",5],["read"],["read"]]
›
Output:
[5]
💡 Note:
Read from empty buffer returns nothing. Add 5 → buffer=[5,null]. Read returns 5. Read from empty buffer again returns nothing.
Example 3 — Overwrite Pattern
$
Input:
capacity = 2, operations = [["add",1],["add",2],["add",3],["add",4],["read"],["read"]]
›
Output:
[3,4]
💡 Note:
Add 1,2 fills buffer. Add 3 overwrites 1, Add 4 overwrites 2. Buffer=[3,4]. Read returns 3, then 4.
Constraints
- 1 ≤ capacity ≤ 1000
- 1 ≤ operations.length ≤ 1000
- operations[i] is either ["add", value] or ["read"]
- -1000 ≤ value ≤ 1000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code