Ring-Buffer Deque with Constant-Time Indexing
Data Structure DesignAuto-graded · 13 test casesLast updated
Build a double-ended queue on a resizable circular array so index lookups are O(1), then replay a command list against it and report each result.
Replaying Commands on an Indexable Deque
A sequence container is needed that lets you add or remove items at either end and also read or overwrite any item by its position, all in constant time. You will build such a container yourself and then drive it with a list of commands.
The container
Elements are ordered from front to back, and positions are numbered from 0 at the front. The container supports these commands:
| Command | Arguments | Effect | Value produced |
|---|---|---|---|
push_front | [val] | Put val before the current front element | None |
push_back | [val] | Put val after the current last element | None |
pop_front | [] | Remove the front element | the removed value |
pop_back | [] | Remove the last element | the removed value |
get | [index] | Read the element at position index | that element |
set | [index, val] | Overwrite the element at position index with val | None |
size | [] | Count the stored elements | the count |
Intended cost targets for the container you design:
get,setandsizetake worst-case O(1) time.push_front,push_back,pop_frontandpop_backtake amortized O(1) time.
Use a plain contiguous list as raw storage and manage the wrap-around and resizing logic yourself. Do not use collections.deque or any other built-in deque type to hold the elements.
The function to write
You are given two lists of equal length:
commands[i]is the name of the i-th command, one of the seven names above.args_list[i]is the list of arguments for that command, exactly as shown in the table.
Starting from an empty container, run the commands in order. Return a list with one entry per command, where entry i is the value produced by command i. Commands that produce no value (push_front, push_back, set) contribute None.
Rules and edge cases
- Indexing is 0-based from the front. Negative indices are not valid.
- The tests only issue valid commands: no pop on an empty container and no
getorsetwith an index outside0 .. size-1. For robustness, a well-behaved implementation should still raiseIndexErrorin those cases. setchanges only the value at that position. It does not change the size or the order of the other elements.- Pushes and pops at both ends can be freely interleaved, including a long run of
push_fronton a brand-new container.
Constraints
1 <= len(commands) == len(args_list) <= 10^5- Stored values are integers in the range
[-10^9, 10^9]. - Every
indexpassed togetorsetsatisfies0 <= index < size()at that moment. - Every
pop_frontandpop_backis issued only when the container is non-empty. - Storage must be built from a plain contiguous array that you manage yourself, not a built-in deque type.
Examples
Example 1
Input: run_indexed_deque_commands(['push_back', 'push_back', 'push_front', 'get', 'get', 'get', 'set', 'get', 'pop_front', 'pop_back', 'size'], [[10], [20], [5], [0], [1], [2], [1, 15], [1], [], [], []])
Output: [None, None, None, 5, 10, 20, None, 15, 5, 20, 1]
Hints
Hint 1
Keep one array plus two integers: where the front element sits in the array, and how many elements are stored. Position i of the deque then lives at (front + i) modulo the array length.
Hint 2
Pushing or popping at the front only moves the front marker backward or forward by one slot (modulo the array length). Nothing needs to be shifted.
Hint 3
When the array is full, allocate one twice as large and copy the elements in logical order (not raw array order) starting at slot 0, then reset the front marker to 0. Optionally shrink when the array is at most a quarter full, so grow and shrink thresholds do not oscillate.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store the elements in a circular buffer: one contiguous array plus two integers.
headis the array slot that holds the front element.countis how many elements are stored.
The element at logical position i is always at slot (head + i) % capacity. Every operation follows from this mapping:
| Operation | Slot used | State change |
|---|---|---|
push_front | (head - 1) % cap | head steps back, count +1 |
push_back | (head + count) % cap | count +1 |
pop_front | head | head steps forward, count -1 |
pop_back | (head + count - 1) % cap | count -1 |
get / set | (head + i) % cap | none |
No elements are ever shifted. Only head and count change.
Growing. If the array is full before a push, allocate an array of double the size. Copy elements in logical order into slots 0 .. count-1 and set head = 0. Copying by logical order is essential: a raw slice of the old array would scramble the data whenever the content wraps around.
Shrinking. After a pop, if the capacity is above the minimum of 8 and count is at most a quarter of the capacity, rebuild into an array of half the size (never below 8). Growing at 100% full and shrinking at 25% full leaves a wide gap, so alternating pushes and pops near a threshold cannot trigger a rebuild on every call.
The driver function creates a fresh container, calls each command by name with its arguments, and appends the result (which is None for pushes and set).
Why it is correct
Invariant: the logical sequence x_0 .. x_{count-1} occupies slots head, head+1, ..., head+count-1, all taken modulo cap.
push_frontmovesheadback one slot and writes there, so the oldx_0becomes logical index 1, as the formula requires.push_backwrites just after the last element. That slot is free because the array was grown first ifcount == cap.pop_frontandpop_backremove an end element and keep the rest contiguous modulocap.- A rebuild places
x_iat slotiwithhead = 0, so the invariant holds trivially afterward.
Because the invariant always holds, get and set are just the mapping formula plus a bounds check.
Complexity
get,set,size: worst-case O(1), as each is one modulo and one array access.- Pushes and pops: amortized O(1). A rebuild costs O(n), but after a doubling the array is half full, so at least
capmore pushes are needed before the next grow. After a halving, the array is half full again, so at leastcap/4further operations are needed before another rebuild. - Space: O(n), since capacity never exceeds
max(8, 4n). - Whole command list of length m: O(m) total time.
Reference solution
from typing import List, Optional
class _RingDeque:
MIN_CAP = 8
def __init__(self):
self.buf = [None] * self.MIN_CAP
self.head = 0
self.count = 0
def _rebuild(self, new_cap):
old_cap = len(self.buf)
new_buf = [None] * new_cap
for i in range(self.count):
new_buf[i] = self.buf[(self.head + i) % old_cap]
self.buf = new_buf
self.head = 0
def _maybe_shrink(self):
cap = len(self.buf)
if cap > self.MIN_CAP and self.count <= cap // 4:
self._rebuild(max(self.MIN_CAP, cap // 2))
def push_front(self, val):
if self.count == len(self.buf):
self._rebuild(len(self.buf) * 2)
self.head = (self.head - 1) % len(self.buf)
self.buf[self.head] = val
self.count += 1
def push_back(self, val):
if self.count == len(self.buf):
self._rebuild(len(self.buf) * 2)
self.buf[(self.head + self.count) % len(self.buf)] = val
self.count += 1
def pop_front(self):
if self.count == 0:
raise IndexError("pop from empty deque")
val = self.buf[self.head]
self.buf[self.head] = None
self.head = (self.head + 1) % len(self.buf)
self.count -= 1
self._maybe_shrink()
return val
def pop_back(self):
if self.count == 0:
raise IndexError("pop from empty deque")
pos = (self.head + self.count - 1) % len(self.buf)
val = self.buf[pos]
self.buf[pos] = None
self.count -= 1
self._maybe_shrink()
return val
def get(self, index):
if index < 0 or index >= self.count:
raise IndexError("deque index out of range")
return self.buf[(self.head + index) % len(self.buf)]
def set(self, index, val):
if index < 0 or index >= self.count:
raise IndexError("deque index out of range")
self.buf[(self.head + index) % len(self.buf)] = val
def size(self):
return self.count
def run_indexed_deque_commands(commands: List[str], args_list: List[List[int]]) -> List[Optional[int]]:
dq = _RingDeque()
out = []
for name, args in zip(commands, args_list):
out.append(getattr(dq, name)(*args))
return out