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 null if 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
INPUTALGORITHMRESULTCapacity: 3012Operations:add(1), add(2), read()add(3), add(4), read(), read()1. Initializehead=0, tail=0, size=02. Add Elementsbuffer[tail] = valuetail = (tail + 1) % capacity3. Read Elementsvalue = buffer[head]head = (head + 1) % capacity4. Handle OverwriteWhen full, overwrite oldestOutput Array[1, 2, 3]Values read in FIFO order:• First read: 1 (oldest)• Second read: 2• Third read: 3Key Insight:Two rotating pointers eliminate the need to search for oldest elements - head tracks reads, tail tracks writesTutorialsPoint - Circular Buffer | Two Pointers with Modulo
Asked in
Google 15 Amazon 22 Microsoft 18 Apple 12
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen