Process a sequence of queue operations and return the values produced by the dequeues, in order. Operations are:
e<x> — enqueue the integer x (e.g. e5).d — dequeue (remove and emit the front value).A d on an empty queue emits nothing. A queue is first-in, first-out.
buildQueue(ops)
Input format: space-separated operations. Output the dequeued values, space-separated.
[e1, e2, d, e3, d, d] // → [1, 2, 3]
[e5, d, d] // → [5]
[d] // → []
Two smaller problems glued together: parsing operations, and simulating a first-in-first-out queue as they're applied. Neither is complicated alone — the value is in keeping the simulation clean.
Whatever was enqueued first comes out first — a checkout line. Enqueue adds to the back; dequeue removes from the front. That's the opposite of a stack (last in, first out). Getting the two confused is the most common way to fail this: enqueue → back, dequeue → front.
A dequeue on an empty queue is a real input scenario, not an error — a no-op. Skipping the check would crash, or silently record undefined if using an array. Explicitly checking keeps the simulation honest.
Only enqueue-at-back and dequeue-from-front are needed, so a plain ordered collection processed linearly is exactly right — no sorting, no searching. n operations cost O(n) time, O(n) space for the recorded output.
def build_queue(ops):
queue = []
out = []
for op in ops:
if op == "d":
if len(queue) > 0:
out.append(queue.pop(0))
elif len(op) > 1 and op[0] == "e":
out_val = int(op[1:])
queue.append(out_val)
return out
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.