Circular Buffer with Fixed Capacity
Data Structure DesignAuto-graded · 16 test casesLast updated
Tests implementation of a bounded FIFO queue using circular array indexing with constant-time operations.
Design and implement a bounded queue data structure using a circular array with fixed capacity. The structure should support standard queue operations with O(1) time complexity.
You will implement a system that processes a sequence of operations on a circular buffer. The operations are:
RingBuffer(capacity): Create a new buffer that can hold at mostcapacityintegers. The storage is preallocated and never resized.push(value): Attempt to add an integer to the rear of the buffer. Returnstrueif successful, orfalseif the buffer is at capacity.pop(): Attempt to remove and retrieve the integer at the front of the buffer. Returns[true, value]if successful, or[false, null]if the buffer is empty.empty(): Returnstrueif the buffer contains no elements,falseotherwise.full(): Returnstrueif the buffer is at capacity,falseotherwise.size(): Returns the current number of elements stored in the buffer.
Write a function that takes two parallel lists: one containing operation names and one containing their arguments. Return a list of results for each operation.
- The first operation is always
RingBufferwith a capacity argument. - Subsequent operations manipulate that buffer instance.
- The
RingBufferconstructor returnsnull.
Constraints:
- 0 ≤ capacity ≤ 10<sup>4</sup>
- 1 ≤ number of operations ≤ 10<sup>4</sup>
- -10<sup>9</sup> ≤ value ≤ 10<sup>9</sup>
- All operations must run in O(1) time
- Space usage must be O(capacity)
- The buffer must correctly handle wrap-around when indices reach the end of the underlying array
Examples
Example 1
Input: ring_buffer_operations(['RingBuffer', 'push', 'push', 'full', 'pop', 'push', 'pop', 'pop', 'empty'], [[3], [10], [20], [], [], [30], [], [], []])
Output: [None, True, True, False, [True, 10], True, [True, 20], [True, 30], True]
Example 2
Input: ring_buffer_operations(['RingBuffer', 'empty', 'full', 'push', 'pop', 'pop', 'size'], [[1], [], [], [7], [], [], []])
Output: [None, True, False, True, [True, 7], [False, None], 0]
Hints
Hint 1
Track both the position of the oldest element and the count of stored elements to avoid ambiguity between empty and full states.
Hint 2
Use modulo arithmetic to wrap indices around when they reach the capacity, creating the circular behavior.
Hint 3
The next insertion position can be computed from the front index and the current count without maintaining a separate tail pointer.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is managing a fixed-size array as a circular structure where elements wrap around to the beginning after reaching the end. We maintain two critical pieces of state:
- Front index: the position of the oldest element (next to be removed)
- Element count: the number of items currently stored
The rear position (where the next insertion occurs) is computed on demand as (front_index + element_count) % capacity. This approach eliminates the ambiguity that arises when tracking front and rear pointers separately, where front equals rear could mean either empty or full.
Push operation: Check if the buffer is at capacity. If not, calculate the rear index, store the value there, and increment the count.
Pop operation: Check if the buffer is empty. If not, retrieve the value at the front index, advance the front index using modulo arithmetic to wrap around, and decrement the count.
Query operations: Directly compare the element count against zero (for empty) or capacity (for full), or return the count itself (for size).
The modulo operator ensures indices wrap around correctly. When an index reaches the capacity, it resets to zero, creating the circular behavior without any manual bounds checking.
Why It Works
The data structure maintains an invariant: the valid elements occupy exactly storage[(front_index + i) % capacity] for i in range [0, element_count), forming a contiguous logical sequence even when physically wrapped.
Initially, with count zero, no positions are valid. Each push adds one element at the computed rear position and extends the valid range by one. Each pop removes the front element and shifts the valid range forward by one. The modulo arithmetic preserves the logical FIFO ordering across physical wrap-around points.
Complexity
Time: O(1) for every operation. Each involves only a constant number of arithmetic operations and array accesses.
Space: O(capacity) for the preallocated storage array, plus O(1) for the bookkeeping variables.
Implementation
from typing import List
def ring_buffer_operations(operations: List[str], arguments: List[List[int]]) -> List[object]:
capacity = None
storage = []
front_index = 0
element_count = 0
results = []
for operation, args in zip(operations, arguments):
if operation == "RingBuffer":
capacity = args[0]
storage = [0] * capacity
front_index = 0
element_count = 0
results.append(None)
elif operation == "push":
if element_count == capacity:
results.append(False)
else:
rear_index = (front_index + element_count) % capacity
storage[rear_index] = args[0]
element_count += 1
results.append(True)
elif operation == "pop":
if element_count == 0:
results.append([False, None])
else:
retrieved_value = storage[front_index]
front_index = (front_index + 1) % capacity
element_count -= 1
results.append([True, retrieved_value])
elif operation == "empty":
results.append(element_count == 0)
elif operation == "full":
results.append(element_count == capacity)
elif operation == "size":
results.append(element_count)
else:
raise ValueError("Unknown operation")
return results