Skip to contentKEEP THE CRAFTTHE SANCTUARY

Deque

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…

Deque Code Labs

Mental Model

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.

Two Ends, One Ordered Sequence

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.

Use Both Ends Deliberately

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.

Route Commands to Both Ends

Reference
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 results
Practice

Implement run_deque_commands(commands). Support append-right, append-left, pop-left, and pop-right; removals return the item or None when empty.

Public tests

  • Verify all four end operations

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Route Commands to Both Ends

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 results

Maintain a Bounded Recent Window

A 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.

Keep Only Recent Values

Reference
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 snapshots
Practice

Implement recent_snapshots(values, capacity). After each append, record the current bounded deque from oldest to newest.

Public tests

  • Verify bounded oldest expiration
  • Verify zero-length boundary

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Keep Only Recent Values

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 snapshots

Trace Expiration and Independent History Snapshots

Run 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.
Print 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 or 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.

Deque Endpoints and Expiration Mistakes

  • Calling pop when FIFO code requires popleft silently reverses processing order.
  • Assuming middle access is O(1) treats a deque like an array.
  • Using maxlen without accounting for the automatically expired item breaks aggregates.
  • Calling rotate repeatedly inside a loop can hide superlinear work.

Explain It in an Interview

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 Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Endpoint append or removalO(1)O(1)Extra working space per operation; stored contents use O(k). Middle indexing and rotation have different costs.
Return bounded snapshotsO(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.

Space

O(1) for endpoint append or removal; O(n * (k + 1)) for return bounded snapshots.

Assumptions

  • Extra working space per operation; stored contents use O(k). Middle indexing and rotation have different costs.
  • n appends, capacity k. Each snapshot copies up to k members and still allocates a list at zero capacity.

Invariants Worth Saying Aloud

  1. Each endpoint has an explicit meaning in the algorithm.
  2. Bounded recent history stores the latest min(processed, capacity) values in arrival order.
  3. Snapshots must own their lists; aggregates must remove expired contributions.

When To Use Or Avoid Deque

Use It When

  • Use deque for both-end operations with an explicit ordering convention.
  • Use maxlen when old history may be discarded automatically.

Choose Another Tool When

  • Use a list for repeated arbitrary indexing.
  • Do not let maxlen expiry bypass independent count or sum updates.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Removing from the wrong endpoint

pop and popleft both succeed but expose opposite order.

Prevent it: Use popleft when the algorithm's oldest member is on the left.

Avoid

removed = items.pop()

Use instead

removed = items.popleft()

Ignoring the defined empty removal result

An empty popleft raises IndexError; the command Lab defines None for absence.

Prevent it: Guard removal when empty is a valid state.

Avoid

removed = items.popleft()

Use instead

removed = items.popleft() if items else None

Keeping an expired value in a running sum

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.

Avoid

items.append(value)
total += value

Use instead

expired = items[0] if len(items) == items.maxlen else 0
items.append(value)
total += value - expired

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.