Skip to content

ORIGINAL CODING QUESTION

Moves inside a two-stack ticket queue

A help desk runs its first-in-first-out ticket queue on two stacks, an inbox and an outbox. Adding a ticket pushes it onto the inbox. Serving a ticket pops the top of the outbox; if the outbox is empty at that moment, every ticket in the inbox is first popped and pushed onto the outbox, one ticket at a time. Serving when both stacks are empty does nothing. Return the total number of tickets moved from the inbox to the outbox over the whole log.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

q, then q operation codes (1 = add a ticket, 2 = serve). Print the number of moved tickets.

Constraints

1 ≤ q ≤ 200; every code is 1 or 2.

Example 1

Input

6
1 1 2 1 2 2

Output

3

The first serve moves 2 tickets, the second serve uses the outbox, and the third serve moves the 1 waiting ticket: 3 moves.

Example 2

Input

3
2 1 2

Output

1

The first serve finds nothing; the later serve moves 1 ticket.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Simulate the two stacks exactly as described.

Hint 2

Moves happen only on a serve that finds the outbox empty.

Hint 3

Each ticket is moved at most once, which is why this queue has amortized constant cost per operation.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →