Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Deque itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Assign a meaning to both deque endpoints before using efficient front and back updates. A bounded deque expires an opposite-end value automatically, so a history snapshot or running aggregate must account for the changed contents.
1 practice exercise3 interview problems
Recognize it when Both oldest and newest endpoint operations affect the answer.
Checking your account…
A deque is one ordered sequence with efficient access to both ends. Unlike a queue, neither end is intrinsically “front” or “back” until the algorithm assigns that meaning. Make the convention explicit: which operation admits new work, which expires old work, and what order remains inside.
collections.deque provides append, appendleft, pop, and popleft in O(1) time at their
respective ends. Middle indexing is not the purpose of the structure. rotate(k) moves items around
the ring; its work depends on the effective rotation distance, so it is not a free whole-deque
reordering operation.
The official deque reference(opens in a new tab)
also documents maxlen, which automatically discards the opposite-end item when a bounded deque is
full.
The operation name must match the intended end. A command runner makes mistakes immediately observable: left insertion followed by right removal is different from an ordinary FIFO queue.
from collections import deque
def run_deque_commands(commands):
items = deque()
results = []
for command in commands:
operation = command[0]
if operation == 'append-right':
items.append(command[1])
elif operation == 'append-left':
items.appendleft(command[1])
elif operation == 'pop-left':
results.append(items.popleft() if items else None)
elif operation == 'pop-right':
results.append(items.pop() if items else None)
return resultsImplement run_deque_commands(commands). Support append-right, append-left, pop-left, and pop-right; removals return the item or None when empty.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
from collections import deque
def run_deque_commands(commands):
items = deque()
results = []
for command in commands:
operation = command[0]
if operation == 'append-right':
items.append(command[1])
elif operation == 'append-left':
items.appendleft(command[1])
elif operation == 'pop-left':
results.append(items.popleft() if items else None)
elif operation == 'pop-right':
results.append(items.pop() if items else None)
return resultsA deque with maxlen=k contains the latest min(processed, k) appended items. Once full, appending a new item
expires the oldest from the left. This is useful for bounded history, but a sliding-window aggregate
still needs explicit updates when an expired value affects a sum, count, minimum, or maximum.
from collections import deque
def recent_snapshots(values, capacity):
recent = deque(maxlen=capacity)
snapshots = []
for value in values:
recent.append(value)
snapshots.append(list(recent))
return snapshotsImplement recent_snapshots(values, capacity). After each append, record the current bounded deque from oldest to newest.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
from collections import deque
def recent_snapshots(values, capacity):
recent = deque(maxlen=capacity)
snapshots = []
for value in values:
recent.append(value)
snapshots.append(list(recent))
return snapshotsRun the actual recent-history Lab with capacity two. The third append is the first expiration, while list(recent) preserves each earlier snapshot independently.
print(recent_snapshots([4, 7, 2], 2)) followed by print(recent_snapshots([4, 7], 0))
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | recent = deque(maxlen=capacity); snapshots = [] |
recent = []; capacity = 2; snapshots = [] |
Only bounded history belongs to the deque. |
| 2 | recent.append(value); snapshots.append(list(recent)) |
value = 4; snapshots = [[4]] |
The first list conversion copies current contents. |
| 3 | recent.append(value); snapshots.append(list(recent)) |
value = 7; recent = [4, 7]; snapshots = [[4], [4, 7]] |
Capacity is full but earlier lists stay independent. |
| 4 | recent.append(value) |
value = 2; expired = 4; recent = [7, 2] |
Right append expires the oldest left member automatically. |
| 5 | snapshots.append(list(recent)); return snapshots |
result = [[4], [4, 7], [7, 2]] |
The new snapshot records recent history without changing prior snapshots. |
| Output | |
|---|---|
| 1 | [[4], [4, 7], [7, 2]] |
| 2 | [[], []] |
Append has constant endpoint cost; copying every returned window adds output work and storage. At capacity zero, every appended value expires immediately and each snapshot is an empty list.
Choose deque for O(1) operations at both ends, a list for indexed access and right-end stack work,
a queue convention when only FIFO behavior matters, and a heap when priority determines removal.
A monotonic deque adds a stronger invariant: its stored candidates are ordered by value as well as
position, allowing obsolete items to leave from one end and dominated items from the other.
pop when FIFO code requires popleft silently reverses processing order.maxlen without accounting for the automatically expired item breaks aggregates.rotate repeatedly inside a loop can hide superlinear work.State the meaning of both ends and the order invariant between them. For a window, say exactly when an index becomes stale and exactly why a candidate may be removed permanently. Count each item by how often it can enter and leave; many deque algorithms are linear because every item is appended once and removed at most once from each end.
Practice Deque Operations(opens in a new tab) establishes the API. Longest Continuous Subarray Within Limit(opens in a new tab) uses two monotonic deques to maintain changing minimum and maximum boundaries.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Deque itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Endpoint append or removal | O(1) | O(1) | Extra working space per operation; stored contents use O(k). Middle indexing and rotation have different costs. |
| Return bounded snapshots | O(n * (k + 1)) | O(n * (k + 1)) | n appends, capacity k. Each snapshot copies up to k members and still allocates a list at zero capacity. |
O(1) for endpoint append or removal; O(n * (k + 1)) for return bounded snapshots.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
pop and popleft both succeed but expose opposite order.
Prevent it: Use popleft when the algorithm's oldest member is on the left.
removed = items.pop()removed = items.popleft()Where you will hit this: Practice Deque Operations(opens in a new tab)
An empty popleft raises IndexError; the command Lab defines None for absence.
Prevent it: Guard removal when empty is a valid state.
removed = items.popleft()removed = items.popleft() if items else NoneWhere you will hit this: Practice Deque Operations(opens in a new tab)
For this running-sum example with positive maxlen, automatic deque eviction does not update a separate total.
Prevent it: For a positive maxlen, read the expiring contribution before append, then subtract it. At maxlen zero no value is retained, so its separate sum stays zero.
items.append(value)
total += valueexpired = items[0] if len(items) == items.maxlen else 0
items.append(value)
total += value - expiredWhere you will hit this: Longest Continuous Subarray Within Limit(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-12