KatInterview

Simulate a Fixed-Capacity Circular Queue

Data Structure DesignAuto-graded · 15 test cases
MediumAuto-gradedData Structure Designcircular-bufferqueuearray

Last updated

Tests ability to implement a circular buffer with O(1) enqueue/dequeue/peek and correct wraparound, full/empty handling, and ordered iteration.

Circular Queue Simulator

You are given a fixed-capacity circular queue backed by an array. Your task is to simulate a sequence of operations on it and return every result in order.

The queue holds at most capacity elements at any time. Internally it uses a fixed-size array and two bookkeeping integers — the index of the oldest element and the current count — so that no operation needs to scan or resize the array.

Operations

Each operation is a string. Some carry an argument; those that do not receive an empty list [].

OperationArgumentReturnsBehavior
push[x]True / FalseAdd x at the back. Returns True on success. If the queue is already full, leaves it unchanged and returns False.
pop[]value or NoneRemove and return the front (oldest) element. Returns None if the queue is empty.
peek[]value or NoneReturn the front element without removing it. Returns None if the queue is empty.
isEmpty[]boolTrue if there are no elements currently stored.
isFull[]boolTrue if the number of stored elements equals capacity.
size[]intNumber of elements currently stored.
iterate[]listAll current elements from oldest to newest as a list.

Rules

  • push on a full queue returns False and does not overwrite any existing element.
  • pop and peek on an empty queue return None (no exception is raised).
  • A capacity that is less than or equal to zero raises a ValueError.
  • An unrecognised operation name raises a ValueError.
  • The output list has exactly one entry per operation, in the same order.

Constraints

  • 1 <= capacity <= 1000
  • 1 <= len(operations) == len(arguments) <= 2000
  • Each push argument is a single integer in the range [-10^6, 10^6].
  • Operations are drawn from: push, pop, peek, isEmpty, isFull, size, iterate.

Examples

Example 1

Input: circular_queue_sim(3, ['push', 'push', 'push', 'isFull', 'push', 'peek', 'iterate', 'pop', 'size', 'iterate'], [[1], [2], [3], [], [4], [], [], [], [], []])

Output: [True, True, True, True, False, 1, [1, 2, 3], 1, 2, [2, 3]]

Hints

Hint 1

Track the front index and the current count. The write position is always (front + count) % capacity — no need to store it separately, and the empty/full ambiguity disappears.

Hint 2

When wrapping around during iterate, don't try to slice the array in two halves. A single loop over i in range(count) using index (front + i) % capacity handles every layout cleanly.

Hint 3

For pop, advance the front index modulo capacity and decrement count. Nulling out the vacated slot isn't required for correctness, but it releases the reference so large objects can be garbage-collected.