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]): Place value at the front end; append None to the returned output list.
  • "pushBack" ([value]): Place value at the back end; append None to the returned output list.
  • "popFront" ([]): Detach and return the front item. Raise an explicit empty-deque exception inside your class when empty, which resizable_deque maps to None.
  • "popBack" ([]): Detach and return the back item. Raise an explicit empty-deque exception inside your class when empty, which resizable_deque maps to None.
  • "peekFront" ([]): Read and return the front item without detaching it (or None via the empty-deque exception when empty).
  • "peekBack" ([]): Read and return the back item without detaching it (or None via the empty-deque exception when empty).
  • "isEmpty" ([]): Return True if zero items are currently stored, else False.
  • "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 (including 0, which must be distinguishable from an empty slot).
  • Do not delegate storage to collections.deque or 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

  1. 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), where operations[i] names the method (such as "pushFront") and arguments[i] holds its argument list ([value] for pushes, [] for everything else). We return one output per operation:

    • pushFront(value) and pushBack(value) return None.
    • popFront(), popBack(), peekFront(), and peekBack() return the front or back value, or None in the judge output when the deque is empty (as shown in Example 3).
    • isEmpty() returns True or False, and size() returns the integer count.

    To satisfy "handle the error clearly" cleanly, our CircularDeque class raises a custom EmptyDequeError (a subclass of IndexError) whenever someone pops or peeks an empty deque, and resizable_deque catches EmptyDequeError to append None for the judge.

  2. 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 (append and pop() 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 n front pushes or front pops in a row then costs 1 + 2 + ... + n = O(n^2) work. The only reason the front was slow is that we insisted the front must live at index 0. If we let the front index move — and wrap around the ends of the array — neither end ever has to shift existing elements.

  3. Key idea: bend the array into a circle with head and count

    Keep three fields inside CircularDeque:

    • data: an array of length capacity (initially 4), filled with None.
    • head: the physical index in data where the front element currently sits.
    • count: how many live elements are currently stored (0 <= count <= capacity).

    From head and count, every logical deque position 0, 1, ..., count - 1 maps 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 offset lives 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 + count instead of head + tail? With only head and tail pointers, both an empty ring and a completely full ring satisfy head == tail! Tracking count removes all ambiguity: empty is count == 0, and full is count == capacity.

  4. Double and unwrap the ring when full

    What happens when count == len(data) and another push arrives? We allocate a new array of 2 * len(data) slots and copy the existing count items 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 when head = 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 = 0
    
  5. Implement 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): moves self.head one slot to the left using (self.head - 1) % len(self.data), writes value into that new front slot, and increments self.count. In Python, (-1) % 4 evaluates to 3, so stepping left from index 0 wraps cleanly to the end of the array.
    • push_back(value): leaves self.head unchanged, writes value into logical offset self.count (the free slot right after the current back element at self.count - 1), and increments self.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 += 1
    
  6. Implement pops, peeks, and queries

    Every pop and peek first checks if self.count == 0: and raises EmptyDequeError immediately — before touching self.data. Notice that a legitimate stored value can be 0 or False, so emptiness must always come from self.count == 0, never from checking whether a slot is None or falsy.

    • pop_front(): reads self.data[self.head], overwrites self.data[self.head] = None (so the array doesn't hold onto removed objects in memory), steps self.head one slot forward with self._physical_index(1), and decrements self.count.
    • pop_back(): reads self.data[back_idx] where back_idx = self._physical_index(self.count - 1), clears that slot to None, and decrements self.count (self.head stays put).
    • peek_front(), peek_back(), is_empty(), size(): read without modifying head or count.
    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.count
    
  7. Connect the judge adapter and trace Example 2

    apply_operation dispatches each operation string to the matching CircularDeque method, and resizable_deque collects the outputs, catching only EmptyDequeError (not every IndexError, which could mask a missing argument in args[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 results
    

    Let'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    2
    

    Notice 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].

  8. 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:

  1. pushFront(10): head wraps to (0 - 1) % 2 = 1; data = [None, 10], head = 1, count = 1.
  2. pushFront(20): head steps to (1 - 1) % 2 = 0; data = [20, 10], head = 0, count = 2 (now full, logical order [20, 10]).
  3. pushBack(30): ring is full (count == 2), so _grow() doubles to capacity 4 (data = [20, 10, None, None], head = 0), then writes 30 at (0 + 2) % 4 = 2 -> data = [20, 10, 30, None], count = 3.
  4. popFront(): returns data[0] = 20, clears data[0] = None, advances head to 1, 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 for popFront, popBack, peekFront, peekBack, isEmpty, and size, because each computes at most one modular index and touches one array slot. pushFront and pushBack run in O(1) amortized time: if the final resize grew capacity from K to 2K, there must have been at least K pushes (n >= K), and the total elements copied across every resize (4 + 8 + 16 + ... + K = 2K - 4) is strictly less than 2n — fewer than two element copies per push on average. Processing all n operations therefore takes O(n) total time.
  • Space: O(m) auxiliary space inside the deque (plus O(n) for the output list returned to the judge). Because we only double from K to 2K when inserting the (K + 1)-th item, the allocated array length never exceeds max(4, 2m).

Edge cases

  • Pop or peek on an empty deque: CircularDeque raises EmptyDequeError, which resizable_deque catches and records as None (Example 3).
  • head stepping backward past 0: push_front when head == 0 wraps cleanly to capacity - 1 via (0 - 1) % capacity.
  • Resizing while wrapped around the array end: _grow() reads elements via _physical_index(0..count - 1), unwrapping the sequence so new_data[0] is always the logical front (head = 0).
  • Repeated queue cycling (pushBack + popFront): head laps around the ring arbitrarily many times without ever resizing as long as count stays <= capacity.
  • Stored 0 or False values: treated as real elements because emptiness checks self.count == 0, never whether self.data[idx] is truthy or None.
  • Emptying and reusing: after count drops to 0, subsequent pushes and pops work regardless of which slot head currently points to.

Common mistakes

  • Copying raw array indices during _grow() (new_data[:cap] = old_data): corrupts the deque order whenever head != 0 because 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 head and tail without count: both empty and full rings satisfy head == tail, causing a full ring to look empty (or overwrite the front element) unless you track count or intentionally waste one slot.
  • Growing by a constant (capacity + 10) instead of doubling: causes O(n) resizes of average size O(n), degrading n pushes to O(n^2) total time.
  • Off-by-one on the back index: the current back element lives at logical offset count - 1, whereas push_back writes into the first empty slot at logical offset count.
  • Catching broad IndexError in the adapter: silently turns genuine bugs (such as args[0] failing on malformed test input) into None; catch a dedicated EmptyDequeError instead.

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, and O(n) indexed lookup. It also violates this problem's requirement to use a circular array.
  • Two dynamic arrays (front stack + back stack): pushFront appends to the front stack and pushBack appends to the back stack; if one stack runs empty during a pop, move half of the other stack over. Still O(1) amortized, though rebalancing and peeking across empty stacks is much trickier than modular ring indexing.
  • Block-linked deque (collections.deque in Python, std::deque in C++): chains fixed-size array blocks together so neither resizing nor pointer-per-element overhead is needed. Always prefer collections.deque in 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 like 4) only when count drops to capacity // 4, not capacity // 2. If you grew at full and shrank at half-full, alternating push and pop right at the boundary would trigger an O(n) copy on every single call (a bug called thrashing, where a data structure repeatedly resizes back and forth on adjacent operations). Shrinking at 1/4 leaves the new array 1/2 full after every resize, guaranteeing at least new_capacity / 2 operations 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 (raising IndexError if out of bounds) and return self.data[(self.head + i) % len(self.data)]. Fast O(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 the 2 * capacity array ahead of time and copy just 2 existing elements into the new array on every push until the migration finishes.

Follow-up questions

Similar questions

More Tml interview questions

All 1 Tml questions →