Resizable Circular-Array Deque
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build a dynamically resizing double-ended queue backed by a circular array (ring buffer), and expose it through resizable_deque(operations, arguments).
Your underlying deque class must store items in a contiguous array whose front and back positions wrap around modulo the buffer length so neither end shifts existing elements. Whenever an insertion arrives while every array slot is occupied, allocate a larger buffer, copy the stored items across in front-to-back sequence order, reset your internal indices, and proceed with the insertion so every operation runs in O(1) amortized time.
Each index i pairs command name operations[i] with parameter list arguments[i] ([value] for insertions, [] otherwise):
"pushFront"([value]): Placevalueat the front end; appendNoneto the returned output list."pushBack"([value]): Placevalueat the back end; appendNoneto the returned output list."popFront"([]): Detach and return the front item. Raise an explicit empty-deque exception inside your class when empty, whichresizable_dequemaps toNone."popBack"([]): Detach and return the back item. Raise an explicit empty-deque exception inside your class when empty, whichresizable_dequemaps toNone."peekFront"([]): Read and return the front item without detaching it (orNonevia the empty-deque exception when empty)."peekBack"([]): Read and return the back item without detaching it (orNonevia the empty-deque exception when empty)."isEmpty"([]): ReturnTrueif zero items are currently stored, elseFalse."size"([]): Return the integer count of currently stored items.
Examples
Example 1
Input:
operations = ["pushBack", "pushBack", "pushFront", "peekFront", "peekBack", "size", "popFront", "popBack", "isEmpty"]
arguments = [[40], [50], [30], [], [], [], [], [], []]
Output:
[None, None, None, 30, 50, 3, 30, 50, False]
Explanation: After inserting 40 and 50 at the back and 30 at the front, the logical order is [30, 40, 50] (peekFront -> 30, peekBack -> 50, size -> 3). Removing 30 from the front and 50 from the back leaves [40], so isEmpty() returns False.
Example 2
Input:
operations = ["pushFront", "pushFront", "pushBack", "pushBack", "pushFront", "size", "popBack", "peekFront"]
arguments = [[8], [4], [12], [16], [2], [], [], []]
Output:
[None, None, None, None, None, 5, 16, 2]
Explanation: Five insertions build [2, 4, 8, 12, 16] across wraparound and automatic capacity expansion (size -> 5). popBack() removes 16, and peekFront() reads 2.
Example 3
Input:
operations = ["isEmpty", "popBack", "peekFront", "pushFront", "popFront", "popFront"]
arguments = [[], [], [], [-9], [], []]
Output:
[True, None, None, None, -9, None]
Explanation: A newly created deque is empty (True), so popBack() and peekFront() raise the empty error and record None. After pushFront(-9), the first popFront() returns -9 and the second popFront() again encounters an empty buffer (None).
Constraints
0 <= len(operations) == len(arguments) <= 10^5- Every
operations[i]is one of"pushFront","pushBack","popFront","popBack","peekFront","peekBack","isEmpty", or"size". -10^9 <= value <= 10^9(including0, which must be distinguishable from an empty slot).- Do not delegate storage to
collections.dequeor linked-list nodes; use a plain fixed-capacity list as a circular buffer with manual resizing. - Every operation must execute in
O(1)amortized time.
Step-by-step walkthrough
Understand the operations and judge contract
A deque (double-ended queue) lets us add, remove, and inspect items at both the front and the back. We must build one on top of a plain fixed-size array used as a circle, doubling that array whenever it fills up so every operation runs in
O(1)amortized time.The judge calls
resizable_deque(operations, arguments), whereoperations[i]names the method (such as"pushFront") andarguments[i]holds its argument list ([value]for pushes,[]for everything else). We return one output per operation:pushFront(value)andpushBack(value)returnNone.popFront(),popBack(),peekFront(), andpeekBack()return the front or back value, orNonein the judge output when the deque is empty (as shown in Example 3).isEmpty()returnsTrueorFalse, andsize()returns the integer count.
To satisfy "handle the error clearly" cleanly, our
CircularDequeclass raises a customEmptyDequeError(a subclass ofIndexError) whenever someone pops or peeks an empty deque, andresizable_dequecatchesEmptyDequeErrorto appendNonefor the judge.Why a plain array is slow at the front
If we store the deque in a normal list with the front element permanently pinned to index
0, the back is fast (appendandpop()touch only the end), but the front has to shift every existing element one slot over:Front pinned at index 0: [20, 10, 30, _] pushFront(99) must shift 30 -> slot 3, 10 -> slot 2, 20 -> slot 1 first: [99, 20, 10, 30] <-- O(n) work for ONE push!Doing
nfront pushes or front pops in a row then costs1 + 2 + ... + n = O(n^2)work. The only reason the front was slow is that we insisted the front must live at index0. If we let the front index move — and wrap around the ends of the array — neither end ever has to shift existing elements.Key idea: bend the array into a circle with head and count
Keep three fields inside
CircularDeque:data: an array of lengthcapacity(initially4), filled withNone.head: the physical index indatawhere the front element currently sits.count: how many live elements are currently stored (0 <= count <= capacity).
From
headandcount, every logical deque position0, 1, ..., count - 1maps onto a physical slot by stepping forward and wrapping around with% capacity:capacity = 4, head = 2, count = 3 Logical deque order: [front = 20, 10, back = 30] Physical array indices: 0 1 2 3 data: [ 30, None, 20, 10 ] ^ ^ back: (2+2)%4=0 head=2 (front)- Logical element
offsetlives at(head + offset) % capacity. - The back element is
offset = count - 1, so(head + count - 1) % capacity. - The first empty slot at the back is
offset = count, so(head + count) % capacity.
Why store
head+countinstead ofhead+tail? With onlyheadandtailpointers, both an empty ring and a completely full ring satisfyhead == tail! Trackingcountremoves all ambiguity: empty iscount == 0, and full iscount == capacity.Double and unwrap the ring when full
What happens when
count == len(data)and another push arrives? We allocate a new array of2 * len(data)slots and copy the existingcountitems over.Crucially, we must copy in logical order (
logical_i = 0, 1, ..., count - 1), not raw physical order! Look at what would happen if we copied raw array slots whenhead = 2:Wrapped full ring (capacity 4, head = 2, count = 4): Logical order: 10, 20, 30, 40 Physical data: [30, 40, 10, 20] (head = 2) WRONG (raw copy): [30, 40, 10, 20, None, None, None, None] -- slots 2 and 3 are no longer adjacent to slot 0! RIGHT (unwrap in logical order 0..3, reset head = 0): [10, 20, 30, 40, None, None, None, None] (head = 0)Let's code the error class, constructor, index helper, and
_grow:class EmptyDequeError(IndexError): """Raised when popping or peeking from an empty deque.""" class CircularDeque: """Resizable double-ended queue backed by a circular array.""" def __init__(self, capacity: int = 4): if capacity < 1: raise ValueError("capacity must be at least 1") # self.data: fixed-size ring buffer of slots, e.g. [30, None, 20, 10] self.data = [None] * capacity # self.head: physical index in self.data where the front element lives self.head = 0 # self.count: number of stored elements (0 == empty, len(self.data) == full) self.count = 0 def _physical_index(self, logical_offset: int) -> int: """Map logical offset (0 = front, count - 1 = back) onto the circular array.""" return (self.head + logical_offset) % len(self.data) def _grow(self) -> None: """Double capacity and unwrap elements into new_data[0..count - 1] in deque order.""" new_capacity = 2 * len(self.data) new_data = [None] * new_capacity # Copy in logical order (front to back), NOT raw array order, because the ring may wrap. for logical_i in range(self.count): physical_i = self._physical_index(logical_i) new_data[logical_i] = self.data[physical_i] self.data = new_data # Logical element 0 now sits at physical index 0. self.head = 0Implement pushFront and pushBack
Both push methods check
if self.count == len(self.data): self._grow()first so there is guaranteed to be at least one free slot:push_front(value): movesself.headone slot to the left using(self.head - 1) % len(self.data), writesvalueinto that new front slot, and incrementsself.count. In Python,(-1) % 4evaluates to3, so stepping left from index0wraps cleanly to the end of the array.push_back(value): leavesself.headunchanged, writesvalueinto logical offsetself.count(the free slot right after the current back element atself.count - 1), and incrementsself.count.
class CircularDeque: # ... (__init__, _physical_index, _grow above) ... def push_front(self, value: object) -> None: if self.count == len(self.data): self._grow() # Step head one slot backward; Python's % wraps -1 to len(self.data) - 1. self.head = (self.head - 1) % len(self.data) self.data[self.head] = value self.count += 1 def push_back(self, value: object) -> None: if self.count == len(self.data): self._grow() # Logical offset `self.count` is the first empty slot immediately past the current back. tail_write_idx = self._physical_index(self.count) self.data[tail_write_idx] = value self.count += 1Implement pops, peeks, and queries
Every pop and peek first checks
if self.count == 0:and raisesEmptyDequeErrorimmediately — before touchingself.data. Notice that a legitimate stored value can be0orFalse, so emptiness must always come fromself.count == 0, never from checking whether a slot isNoneor falsy.pop_front(): readsself.data[self.head], overwritesself.data[self.head] = None(so the array doesn't hold onto removed objects in memory), stepsself.headone slot forward withself._physical_index(1), and decrementsself.count.pop_back(): readsself.data[back_idx]whereback_idx = self._physical_index(self.count - 1), clears that slot toNone, and decrementsself.count(self.headstays put).peek_front(),peek_back(),is_empty(),size(): read without modifyingheadorcount.
class CircularDeque: # ... (earlier methods above) ... def pop_front(self) -> object: if self.count == 0: raise EmptyDequeError("pop_front from an empty deque") value = self.data[self.head] # Clear the vacated slot so the buffer does not keep removed objects alive in memory. self.data[self.head] = None self.head = self._physical_index(1) self.count -= 1 return value def pop_back(self) -> object: if self.count == 0: raise EmptyDequeError("pop_back from an empty deque") back_idx = self._physical_index(self.count - 1) value = self.data[back_idx] self.data[back_idx] = None self.count -= 1 return value def peek_front(self) -> object: if self.count == 0: raise EmptyDequeError("peek_front on an empty deque") return self.data[self.head] def peek_back(self) -> object: if self.count == 0: raise EmptyDequeError("peek_back on an empty deque") back_idx = self._physical_index(self.count - 1) return self.data[back_idx] def is_empty(self) -> bool: return self.count == 0 def size(self) -> int: return self.countConnect the judge adapter and trace Example 2
apply_operationdispatches each operation string to the matchingCircularDequemethod, andresizable_dequecollects the outputs, catching onlyEmptyDequeError(not everyIndexError, which could mask a missing argument inargs[0]).def apply_operation(dq: CircularDeque, op: str, args: List[int]) -> object: """Dispatch a single judge command onto the CircularDeque instance.""" if op == "pushFront": dq.push_front(args[0]) return None if op == "pushBack": dq.push_back(args[0]) return None if op == "popFront": return dq.pop_front() if op == "popBack": return dq.pop_back() if op == "peekFront": return dq.peek_front() if op == "peekBack": return dq.peek_back() if op == "isEmpty": return dq.is_empty() if op == "size": return dq.size() raise ValueError("unknown operation: " + op) def resizable_deque(operations: List[str], arguments: List[List[int]]) -> List[object]: dq = CircularDeque() results = [] for i in range(len(operations)): try: result = apply_operation(dq, operations[i], arguments[i]) results.append(result) except EmptyDequeError: # Catch only EmptyDequeError (not generic IndexError) so empty pops/peeks map to None # without hiding malformed argument lists. results.append(None) return resultsLet's trace Example 2 starting from
data = [_, _, _, _],head = 0,count = 0:Operation Action data head count Output -------------- ---------------------------------------- ------------------------------ ---- ----- ------ pushFront(8) head = (0 - 1) % 4 = 3 [_, _, _, 8] 3 1 None pushFront(4) head = (3 - 1) % 4 = 2 [_, _, 4, 8] 2 2 None pushBack(12) slot = (2 + 2) % 4 = 0 [12, _, 4, 8] 2 3 None pushBack(16) slot = (2 + 3) % 4 = 1 [12, 16, 4, 8] 2 4 None pushFront(2) _grow() unwraps -> [4,8,12,16,_,_,_,_]; [4, 8, 12, 16, _, _, _, 2] 7 5 None head = (0 - 1) % 8 = 7 size() return count -> 5 [4, 8, 12, 16, _, _, _, 2] 7 5 5 popBack() back = (7 + 5 - 1) % 8 = 3 -> 16 [4, 8, 12, _, _, _, _, 2] 7 4 16 peekFront() read data[head = 7] -> 2 [4, 8, 12, _, _, _, _, 2] 7 4 2Notice how
[4, 8, 12, 16]wrapped around the 4-slot ring, unwrapped cleanly into[4, 8, 12, 16, _, _, _, _]on the 5th push, and produced[None, None, None, None, None, 5, 16, 2].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class EmptyDequeError(IndexError): """Raised when popping or peeking from an empty deque.""" class CircularDeque: """Resizable double-ended queue backed by a circular array.""" def __init__(self, capacity: int = 4): if capacity < 1: raise ValueError("capacity must be at least 1") # self.data: fixed-size ring buffer of slots, e.g. [30, None, 20, 10] self.data = [None] * capacity # self.head: physical index in self.data where the front element lives self.head = 0 # self.count: number of stored elements (0 == empty, len(self.data) == full) self.count = 0 def _physical_index(self, logical_offset: int) -> int: """Map logical offset (0 = front, count - 1 = back) onto the circular array.""" return (self.head + logical_offset) % len(self.data) def _grow(self) -> None: """Double capacity and unwrap elements into new_data[0..count - 1] in deque order.""" new_capacity = 2 * len(self.data) new_data = [None] * new_capacity # Copy in logical order (front to back), NOT raw array order, because the ring may wrap. for logical_i in range(self.count): physical_i = self._physical_index(logical_i) new_data[logical_i] = self.data[physical_i] self.data = new_data # Logical element 0 now sits at physical index 0. self.head = 0 def push_front(self, value: object) -> None: if self.count == len(self.data): self._grow() # Step head one slot backward; Python's % wraps -1 to len(self.data) - 1. self.head = (self.head - 1) % len(self.data) self.data[self.head] = value self.count += 1 def push_back(self, value: object) -> None: if self.count == len(self.data): self._grow() # Logical offset `self.count` is the first empty slot immediately past the current back. tail_write_idx = self._physical_index(self.count) self.data[tail_write_idx] = value self.count += 1 def pop_front(self) -> object: if self.count == 0: raise EmptyDequeError("pop_front from an empty deque") value = self.data[self.head] # Clear the vacated slot so the buffer does not keep removed objects alive in memory. self.data[self.head] = None self.head = self._physical_index(1) self.count -= 1 return value def pop_back(self) -> object: if self.count == 0: raise EmptyDequeError("pop_back from an empty deque") back_idx = self._physical_index(self.count - 1) value = self.data[back_idx] self.data[back_idx] = None self.count -= 1 return value def peek_front(self) -> object: if self.count == 0: raise EmptyDequeError("peek_front on an empty deque") return self.data[self.head] def peek_back(self) -> object: if self.count == 0: raise EmptyDequeError("peek_back on an empty deque") back_idx = self._physical_index(self.count - 1) return self.data[back_idx] def is_empty(self) -> bool: return self.count == 0 def size(self) -> int: return self.count def apply_operation(dq: CircularDeque, op: str, args: List[int]) -> object: """Dispatch a single judge command onto the CircularDeque instance.""" if op == "pushFront": dq.push_front(args[0]) return None if op == "pushBack": dq.push_back(args[0]) return None if op == "popFront": return dq.pop_front() if op == "popBack": return dq.pop_back() if op == "peekFront": return dq.peek_front() if op == "peekBack": return dq.peek_back() if op == "isEmpty": return dq.is_empty() if op == "size": return dq.size() raise ValueError("unknown operation: " + op) def resizable_deque(operations: List[str], arguments: List[List[int]]) -> List[object]: dq = CircularDeque() results = [] for i in range(len(operations)): try: result = apply_operation(dq, operations[i], arguments[i]) results.append(result) except EmptyDequeError: # Catch only EmptyDequeError (not generic IndexError) so empty pops/peeks map to None # without hiding malformed argument lists. results.append(None) return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine chairs arranged around a circular carousel instead of a straight row against a wall. In a straight row where the front person must always sit in chair 0, everyone has to stand up and scoot one seat over whenever someone joins or leaves at the front. On a circular carousel, nobody seated ever moves: if someone joins at the front, you simply move the "Front" marker one chair counterclockwise; if someone joins at the back, they take the next empty chair clockwise!
A deque (a double-ended queue that supports inserting and removing items at both ends) needs that exact carousel trick. Using a naive array with the front pinned to index 0 forces pushFront and popFront to shift all k stored elements (O(k) work per call), so n front operations take O(n^2) time. Likewise, if you grow a full array by adding a fixed constant like + 10 slots instead of doubling it, you end up copying the whole array every 10 pushes, which also degrades to O(n^2) total work.
Instead, we store elements in a circular array (a fixed-length array whose last slot wraps around to slot 0, also called a ring buffer) using modular arithmetic (remainder division % capacity so indices wrap back to 0 after capacity - 1). We track head (the physical slot of the front element) and count (how many elements are stored), mapping logical position i (0 is front, count - 1 is back) to (head + i) % capacity. Whenever count == capacity, we allocate an array of size 2 * capacity, copy all count items in logical front-to-back order into new_data[0..count - 1], and reset head = 0. Doubling gives amortized O(1) time (even though an occasional resize takes O(count) steps, the total work averaged per operation over any sequence of n operations is still bounded by a small constant). When popping, we also overwrite the vacated slot with None to prevent a loitering reference (an unused array slot still pointing to a removed object and blocking garbage collection).
Let's trace a tiny example starting with capacity = 2, data = [None, None], head = 0, count = 0:
pushFront(10):headwraps to(0 - 1) % 2 = 1;data = [None, 10],head = 1,count = 1.pushFront(20):headsteps to(1 - 1) % 2 = 0;data = [20, 10],head = 0,count = 2(now full, logical order[20, 10]).pushBack(30): ring is full (count == 2), so_grow()doubles to capacity4(data = [20, 10, None, None],head = 0), then writes30at(0 + 2) % 4 = 2->data = [20, 10, 30, None],count = 3.popFront(): returnsdata[0] = 20, clearsdata[0] = None, advancesheadto1,count = 2(logical order is now[10, 30]).
Complexity
Let n be the total number of operations and m be the maximum number of elements stored in the deque at any point (m <= n).
- Time:
O(1)worst-case time forpopFront,popBack,peekFront,peekBack,isEmpty, andsize, because each computes at most one modular index and touches one array slot.pushFrontandpushBackrun inO(1)amortized time: if the final resize grew capacity fromKto2K, there must have been at leastKpushes (n >= K), and the total elements copied across every resize (4 + 8 + 16 + ... + K = 2K - 4) is strictly less than2n— fewer than two element copies per push on average. Processing allnoperations therefore takesO(n)total time. - Space:
O(m)auxiliary space inside the deque (plusO(n)for the output list returned to the judge). Because we only double fromKto2Kwhen inserting the(K + 1)-th item, the allocated array length never exceedsmax(4, 2m).
Edge cases
- Pop or peek on an empty deque:
CircularDequeraisesEmptyDequeError, whichresizable_dequecatches and records asNone(Example 3). headstepping backward past0:push_frontwhenhead == 0wraps cleanly tocapacity - 1via(0 - 1) % capacity.- Resizing while wrapped around the array end:
_grow()reads elements via_physical_index(0..count - 1), unwrapping the sequence sonew_data[0]is always the logical front (head = 0). - Repeated queue cycling (
pushBack+popFront):headlaps around the ring arbitrarily many times without ever resizing as long ascountstays<= capacity. - Stored
0orFalsevalues: treated as real elements because emptiness checksself.count == 0, never whetherself.data[idx]is truthy orNone. - Emptying and reusing: after
countdrops to0, subsequent pushes and pops work regardless of which slotheadcurrently points to.
Common mistakes
- Copying raw array indices during
_grow()(new_data[:cap] = old_data): corrupts the deque order wheneverhead != 0because newly appended empty slots get inserted into the middle of a wrapped sequence. - Negative modulo in C++, Java, or Go: in Python
(-1) % 4 == 3, whereas in C++/Java/Go-1 % 4 == -1; in those languages always write(head - 1 + capacity) % capacity. - Tracking
headandtailwithoutcount: both empty and full rings satisfyhead == tail, causing a full ring to look empty (or overwrite the front element) unless you trackcountor intentionally waste one slot. - Growing by a constant (
capacity + 10) instead of doubling: causesO(n)resizes of average sizeO(n), degradingnpushes toO(n^2)total time. - Off-by-one on the back index: the current back element lives at logical offset
count - 1, whereaspush_backwrites into the first empty slot at logical offsetcount. - Catching broad
IndexErrorin the adapter: silently turns genuine bugs (such asargs[0]failing on malformed test input) intoNone; catch a dedicatedEmptyDequeErrorinstead.
Alternative approaches
- Doubly linked list: every push and pop is
O(1)worst-case (no resize spikes), at the cost of per-node object and pointer overhead, worse CPU cache locality, andO(n)indexed lookup. It also violates this problem's requirement to use a circular array. - Two dynamic arrays (front stack + back stack):
pushFrontappends to the front stack andpushBackappends to the back stack; if one stack runs empty during a pop, move half of the other stack over. StillO(1)amortized, though rebalancing and peeking across empty stacks is much trickier than modular ring indexing. - Block-linked deque (
collections.dequein Python,std::dequein C++): chains fixed-size array blocks together so neither resizing nor pointer-per-element overhead is needed. Always prefercollections.dequein production Python.
Follow-up questions
- How should the backing array shrink after many removals without losing O(1) amortized performance? Shrink to
capacity // 2(down to a minimum floor like4) only whencountdrops tocapacity // 4, notcapacity // 2. If you grew at full and shrank at half-full, alternatingpushandpopright at the boundary would trigger anO(n)copy on every single call (a bug called thrashing, where a data structure repeatedly resizes back and forth on adjacent operations). Shrinking at1/4leaves the new array1/2full after every resize, guaranteeing at leastnew_capacity / 2operations before the next resize. - How can you add O(1) random access by logical index get(i) to this circular-array deque? Check
0 <= i < self.count(raisingIndexErrorif out of bounds) and returnself.data[(self.head + i) % len(self.data)]. FastO(1)random access is one of the biggest practical advantages of a circular array over a doubly linked list. - When is amortized O(1) latency unacceptable in production, and how can resizing be made worst-case O(1)? In hard real-time systems (such as audio DSP or robotics control loops), a single push that pauses to copy a million elements can miss a strict latency deadline even if the average cost is tiny. You can achieve worst-case
O(1)pushes by incremental resizing: allocate the2 * capacityarray ahead of time and copy just 2 existing elements into the new array on every push until the migration finishes.
Follow-up questions
- How should the backing array shrink after many removals without losing O(1) amortized performance?
- How can you add O(1) random access by logical index get(i) to this circular-array deque?
- When is amortized O(1) latency unacceptable in production, and how can resizing be made worst-case O(1)?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array