Deque Commands With Errors
Programming Interview
Hard
4 views
Problem Description
You will receive q commands: PUSHFRONT x, PUSHBACK x, POPFRONT, POPBACK. Start empty. On POP when empty, output ERROR and stop. Else after all commands output final deque as space-separated or EMPTY.
Input Format
First line q. Next q lines commands.
Output Format
One line result or ERROR.
Sample Test Case
Input:
6
PUSHBACK 1
PUSHFRONT 2
POPBACK
POPFRONT
PUSHBACK 5
POPFRONT
Official Solution
import sys
from collections import deque
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
q=int(lines[0].strip())
dq=deque()
for i in range(1,1+q):
parts=(lines[i] if i<len(lines) else '').split()
if not parts:
continue
cmd=parts[0]
if cmd=='PUSHFRONT':
dq.appendleft(parts[1])
elif cmd=='PUSHBACK':
dq.append(parts[1])
elif cmd=='POPFRONT':
if not dq:
sys.stdout.write('ERROR')
raise SystemExit
dq.popleft()
elif cmd=='POPBACK':
if not dq:
sys.stdout.write('ERROR')
raise SystemExit
dq.pop()
else:
sys.stdout.write('ERROR')
raise SystemExit
sys.stdout.write('EMPTY' if not dq else ' '.join(dq))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!