Practice Deque Operations
Checking your account…
Sign in to save your code and progress across devices. The lesson and problem statement remain public.
Loading the interactive Practice workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Practice workspace
Problem
Implement run_deque_commands(commands). Commands are ["append-right", value], ["append-left", value], ["pop-left"], or ["pop-right"]. Return one result for every pop; an empty pop returns None.
Starter code
from collections import deque
def run_deque_commands(commands):
passTest cases
mixed-ends
{
"args": [
[
[
"append-right",
2
],
[
"append-left",
1
],
[
"pop-right"
],
[
"pop-left"
]
]
]
}Expected: [2,1]
empty-removals
{
"args": [
[
[
"pop-left"
],
[
"pop-right"
]
]
]
}Expected: [null,null]
Wizard outline
- Step 1: Guard an empty removal
Create persistent deque state and record None for an empty pop-left command. An explicit empty policy prevents IndexError before mutation commands are introduced.
- Step 2: Operate on the right end
Append supplied values on the right and remove the newest right-side value safely. Right-side append and pop establish the familiar stack-shaped half of deque behavior.
- Step 3: Operate on the left end
Insert values on the left while preserving both right-side operations. appendleft adds the operation that distinguishes deque from a plain list stack.
Footguns and prerequisites
- Using list.pop(0) makes repeated left removals linear.
- Calling popleft or pop on an empty deque raises IndexError unless guarded.
- python specific rapid fire
Reviewed references
Recommended approach and implementation
Process the command stream once with collections.deque and collect only pop results.
Why it works: Each command invokes the matching deque end operation, and guarded removals return exactly the requested value or None when no value exists.
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