Circular Buffer Deque with Auto-Resize
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests ability to build a double-ended queue on a ring-indexed array that doubles in capacity when full, keeping all operations amortized O(1).
Circular Buffer Deque with Auto-Resize
Build a double-ended queue (deque) using a circular array as the backing store. The array must grow automatically when it runs out of room.
A driver function replays a sequence of named operations on a single deque instance and collects one output value per operation. You implement that driver.
Operations
| Name | Argument(s) | What it does | Output |
|---|---|---|---|
pushFront | value | Insert value at the front | None |
pushBack | value | Insert value at the back | None |
popFront | — | Remove and return the front element | removed value, or None if empty |
popBack | — | Remove and return the back element | removed value, or None if empty |
peekFront | — | Return the front element without removing it | front value, or None if empty |
peekBack | — | Return the back element without removing it | back value, or None if empty |
isEmpty | — | Check whether the deque holds any elements | True or False |
size | — | Count of elements currently stored | integer |
pop and peek on an empty deque must return None without raising an exception. An unrecognised operation name must raise ValueError.
Implementation requirements
- Use a plain array (Python list) as internal storage.
- Index into the array using circular (modulo) arithmetic so that both ends can be reached in O(1).
- Start with an initial capacity of 4. When the array is full and a push arrives, double the capacity: allocate a new array of twice the size, copy all elements in logical front-to-back order into the new array starting at index 0, and reset the front pointer to 0.
- Every operation must run in O(1) amortized time.
Function signature
def circular_deque(operations: List[str], arguments: List[List[int]]) -> List[object]:
operations: a list of operation name strings (see table above).arguments: a parallel list; each entry is a list. For operations that take a value argument the list contains one integer; for operations with no argument the list is empty.- Returns a list with one entry per operation, following the output rules in the table.
Constraints
- 1 ≤ len(operations) ≤ 10,000
- len(operations) == len(arguments)
- Each value passed to a push operation is a 32-bit signed integer.
- The only valid operation names are the eight listed above; any other name must raise
ValueError. - Initial backing-array capacity is exactly 4; capacity doubles on every resize.
popandpeekon an empty deque returnNone(no exception).
Examples
Example 1
Input: circular_deque(['pushBack', 'pushBack', 'peekFront', 'peekBack', 'size', 'popFront', 'popBack', 'isEmpty'], [[1], [2], [], [], [], [], [], []])
Output: [None, None, 1, 2, 2, 1, 2, True]
Example 2
Input: circular_deque(['pushFront', 'pushFront', 'pushBack', 'popBack', 'peekFront', 'size'], [[10], [20], [30], [], [], []])
Output: [None, None, None, 30, 20, 2]
Example 3
Input: circular_deque(['popFront', 'peekBack', 'isEmpty', 'pushBack', 'popBack', 'popBack'], [[], [], [], [-5], [], []])
Output: [None, None, True, None, -5, None]
Hints
Hint 1
Track the deque's state with just two variables — the physical index of the front element and the current count of stored elements. The back index is always derivable from those two, which sidesteps the empty-vs-full ambiguity you get when storing both front and back pointers.
Hint 2
For pushFront, move the front pointer one slot backward before writing: `front = (front - 1) % capacity`. Python's modulo always returns a non-negative result, so this wraps correctly even when front is 0.
Hint 3
When the array is full and needs to grow, don't copy the raw physical layout into the new array — copy in *logical* order (element 0 through element size-1 using the circular formula) and set front back to 0. If the contents have wrapped around, a straight copy will corrupt every subsequent index calculation.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core invariant
The solution tracks only two pieces of mutable state beyond the array itself: front (the physical array index of the logical first element) and size (how many elements are stored). Every other index is derived:
- logical element
ilives at physical index(front + i) % capacity - the back element is at
(front + size - 1) % capacity - the next free slot at the back is
(front + size) % capacity
Using size instead of a separate back pointer cleanly eliminates the classic ambiguity where front == back could mean either "empty" or "full". Empty is simply size == 0; full is size == capacity.
Operations
pushFront — step the front pointer one slot backward with wraparound (front = (front - 1) % capacity), write the value there, then increment size. Python's % always returns a non-negative result, so (0 - 1) % 4 == 3 wraps correctly without any special case.
pushBack — write to (front + size) % capacity, then increment size. The front pointer doesn't move.
popFront — read data[front], clear the slot, advance front = (front + 1) % capacity, decrement size.
popBack — read data[(front + size - 1) % capacity], clear the slot, decrement size. The front pointer doesn't move.
peek variants — same index arithmetic as the corresponding pop, but no pointer or size update.
isEmpty / size — direct reads from size.
Any unrecognised operation name raises ValueError.
Resizing
Before either push, if size == capacity the backing array is full. The resize step:
- Allocates a new array of
2 * capacity. - Copies elements in logical order:
new_data[i] = data[(front + i) % capacity]foriin0..size-1. This "unrolls" any wrap-around so the logical sequence sits contiguously starting at index 0. - Sets
front = 0and replaces the old array.
The unrolling step is the critical detail. A naive slice copy (new_data[:capacity] = data) preserves the physical layout. If the contents had wrapped around the end of the old array, the elements would be out of logical order in the new one, and every subsequent index calculation would produce wrong results.
Why this is correct
The invariant — logical element i is at physical index (front + i) % capacity — holds after every operation:
- pushFront decrements
frontand incrementssize; the new value becomes logical index 0 while all old elements' logical indices increase by 1 with their physical slots unchanged. - pushBack writes at logical index
sizethen incrementssize. - popFront advances
frontand decrementssize; old logical indexi+1becomesiat the same physical slot. - popBack decrements
size, dropping the last logical slot. - resize rebuilds the array so the invariant holds fresh with
front = 0and the new capacity.
Because a push always resizes before writing, a new value never overwrites a live element.
Complexity
Time: all operations are O(1) except a resize, which copies size elements and costs O(n). Capacity doubles at sizes 4, 8, 16, …, so the total copy work over n pushes is at most 4 + 8 + … + n < 2n, giving O(1) amortized per push. All other operations are O(1) worst-case.
Space: O(capacity), which is at most roughly twice the peak number of elements ever stored, so O(n). The output list adds O(m) for m operations.
Edge cases covered
- Pop or peek on an empty deque returns
Nonewithout raising. pushFronton a fresh deque wraps to indexcapacity - 1.- Resize while the contents have wrapped around correctly unrolls them.
- Mixed front/back operations exercise both derived index formulas.
- Cleared slots are set to
Noneto release object references.
Reference solution
from typing import List
def circular_deque(operations: List[str], arguments: List[List[int]]) -> List[object]:
capacity = 4
data = [None] * capacity
front = 0 # physical index of the logical first element
size = 0 # number of stored elements
result = []
def resize():
nonlocal data, capacity, front
new_capacity = capacity * 2
new_data = [None] * new_capacity
# Copy in logical order so the ring is "unrolled" into [0, size).
for i in range(size):
new_data[i] = data[(front + i) % capacity]
data = new_data
capacity = new_capacity
front = 0
for operation, args in zip(operations, arguments):
if operation == "pushFront":
if size == capacity:
resize()
front = (front - 1) % capacity
data[front] = args[0]
size += 1
result.append(None)
elif operation == "pushBack":
if size == capacity:
resize()
data[(front + size) % capacity] = args[0]
size += 1
result.append(None)
elif operation == "popFront":
if size == 0:
result.append(None)
else:
value = data[front]
data[front] = None
front = (front + 1) % capacity
size -= 1
result.append(value)
elif operation == "popBack":
if size == 0:
result.append(None)
else:
index = (front + size - 1) % capacity
value = data[index]
data[index] = None
size -= 1
result.append(value)
elif operation == "peekFront":
result.append(None if size == 0 else data[front])
elif operation == "peekBack":
if size == 0:
result.append(None)
else:
result.append(data[(front + size - 1) % capacity])
elif operation == "isEmpty":
result.append(size == 0)
elif operation == "size":
result.append(size)
else:
raise ValueError(f"Unknown operation: {operation}")
return result