Simulate a Fixed-Capacity Circular Queue
Data Structure DesignAuto-graded · 15 test casesLast 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 [].
| Operation | Argument | Returns | Behavior |
|---|---|---|---|
push | [x] | True / False | Add x at the back. Returns True on success. If the queue is already full, leaves it unchanged and returns False. |
pop | [] | value or None | Remove and return the front (oldest) element. Returns None if the queue is empty. |
peek | [] | value or None | Return the front element without removing it. Returns None if the queue is empty. |
isEmpty | [] | bool | True if there are no elements currently stored. |
isFull | [] | bool | True if the number of stored elements equals capacity. |
size | [] | int | Number of elements currently stored. |
iterate | [] | list | All current elements from oldest to newest as a list. |
Rules
pushon a full queue returnsFalseand does not overwrite any existing element.popandpeekon an empty queue returnNone(no exception is raised).- A
capacitythat is less than or equal to zero raises aValueError. - An unrecognised operation name raises a
ValueError. - The output list has exactly one entry per operation, in the same order.
Constraints
1 <= capacity <= 10001 <= len(operations) == len(arguments) <= 2000- Each
pushargument 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Invariant
Store the queue's state in three variables alongside the fixed array:
data— the backing array of lengthcapacity, allocated once.front— the array index of the oldest (front) element.count— how many elements are currently stored.
From these, the write position (the slot just past the newest element) is always (front + count) % capacity. This derived formula is the key insight: it means you never need a separate rear pointer, and there is no ambiguity between "empty" and "full" (which would arise if you tracked two indices and compared them).
The invariant that every operation preserves: the current elements, from oldest to newest, occupy indices (front + i) % capacity for i in 0..count-1, and 0 <= count <= capacity.
Operation by Operation
push — if count == capacity the queue is full; return False and change nothing. Otherwise write x at (front + count) % capacity, increment count, and return True. The new element is naturally at the back.
pop — if count == 0 return None. Otherwise read data[front], null out that slot (so large objects can be garbage-collected), advance front one step modulo capacity, and decrement count. The remaining elements still satisfy the invariant.
peek — return data[front] if count > 0, else None. No state changes.
isEmpty / isFull / size — direct comparisons or return of count. All O(1).
iterate — build a list by walking i from 0 to count - 1 and computing data[(front + i) % capacity]. This naturally handles wraparound without splitting the array into two slices.
Edge cases handled:
capacity <= 0raisesValueErrorimmediately (also avoids modulo-by-zero).capacity == 1works without special-casing;frontstays at 0 and the buffer alternates between full and empty.- Unknown operation names raise
ValueError. pop/peekon an empty queue returnNonerather than raising, matching the specified contract.
Complexity
| Operation | Time | Space |
|---|---|---|
push, pop, peek | O(1) | O(1) |
isEmpty, isFull, size | O(1) | O(1) |
iterate | O(n) | O(n) output |
| Overall for Q operations | O(Q + total iterated) | O(capacity) backing array |
The backing array is allocated once and never resized, which is the defining advantage of a ring buffer in latency-sensitive systems.
Full Reference Solution
from typing import List
def circular_queue_sim(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[object]:
if capacity <= 0:
raise ValueError("capacity must be positive")
data = [None] * capacity # fixed backing array
front = 0 # index of the oldest element
count = 0 # number of elements currently stored
results = []
for operation, args in zip(operations, arguments):
if operation == "push":
value = args[0]
if count == capacity: # full: reject
results.append(False)
else:
data[(front + count) % capacity] = value
count += 1
results.append(True)
elif operation == "pop":
if count == 0:
results.append(None)
else:
value = data[front]
data[front] = None # release reference
front = (front + 1) % capacity
count -= 1
results.append(value)
elif operation == "peek":
results.append(None if count == 0 else data[front])
elif operation == "isEmpty":
results.append(count == 0)
elif operation == "isFull":
results.append(count == capacity)
elif operation == "size":
results.append(count)
elif operation == "iterate":
results.append([data[(front + i) % capacity] for i in range(count)])
else:
raise ValueError(f"unknown operation: {operation}")
return results