KatInterview

Circular Buffer with Fixed Capacity

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designqueuecircular-bufferarray

Last 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 most capacity integers. The storage is preallocated and never resized.
  • push(value): Attempt to add an integer to the rear of the buffer. Returns true if successful, or false if 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(): Returns true if the buffer contains no elements, false otherwise.
  • full(): Returns true if the buffer is at capacity, false otherwise.
  • 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 RingBuffer with a capacity argument.
  • Subsequent operations manipulate that buffer instance.
  • The RingBuffer constructor returns null.

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.