Skip to content

Pattern · Interview prep

Queue

Serve items in the order they arrived. New work joins the back. The next item to handle is the one that has been waiting longest.

What it is

What is the queue pattern?

A queue is first-in, first-out. You enqueue at the back and dequeue at the front. The item that arrived first leaves first. That is the opposite of a stack, which always resolves the newest open item.

  • One line. Push joins the back. Pop and peek use the front. An empty line has nothing to serve.
  • Two stacks. One stack receives new values. The other serves them. Pour from the first into the second only when the second is empty, so the order reverses once and the oldest value comes out first.
After push 1, then push 2
next1

1 arrived first, so it leaves first

LFrontRBack
A queue holding 1, 2, 3, 4 from front to back. Item 1, the oldest, is dequeued from the front and a new item 5 is enqueued at the back. The queue then holds 2, 3, 4, 5, so items leave in the order they arrived.
The oldest item leaves at the front. The new item waits at the back.

When to use it

How do you recognize a queue problem?

Read the statement for these signals before you reach for the newest item.

Phrases to watch for

  • first in, first out
  • waiting line
  • order of arrival
  • level order
  • breadth
  • the earliest value
  • simulate a queue
  1. 1

    Order of arrival is the order of service

    The front is the value that was pushed earliest, not the one that just arrived.

  2. 2

    You process one layer before the next

    Neighbors discovered now should wait until every neighbor discovered earlier has been handled.

  3. 3

    You have stacks, and you need a line

    Two stacks can imitate a queue if you reverse the line only when the serving stack is empty.

Looks similar, but isn’t

  • The next item is the most recent one

    A closer, an undo, or the nearest waiting index belongs on a Stack. Serving that top would reverse the line.

  • You are keeping a moving slice

    Sliding Window adds one end and drops the other. A deque can hold that slice, but the pattern is the window, not the line of arrivals.

  • You need the best item, not the oldest

    A heap returns the current smallest or largest. A queue returns whoever has waited longest, whatever their value.

Worked example

How do two stacks behave as a queue?

Commands arrive in order. "push N" adds N at the back. "pop" removes the front. "peek" reads the front and leaves it. A pop or peek on an empty line records null, and a push records null too, so there is one result per command. This is the queue you can practice below.

TypeScriptrunQueue
function runQueue(commands: string[]): Array<number | null> {  const inbound: number[] = [];  const outbound: number[] = [];  const recorded: Array<number | null> = [];   const pour = () => {    if (outbound.length > 0) return;    while (inbound.length > 0) outbound.push(inbound.pop() as number);  };   for (const command of commands) {    if (command.startsWith('push ')) {      inbound.push(Number(command.slice(5)));      recorded.push(null);      continue;    }    pour();    if (outbound.length === 0) {      recorded.push(null);      continue;    }    // Peek reads the front. Pop removes it. Both see the oldest value.    recorded.push(command === 'peek' ? outbound[outbound.length - 1] : (outbound.pop() as number));  }   return recorded;}

Pour only when the serving stack is empty, then read its top.

Code is shown in TypeScript. You can solve problems in TypeScript, JavaScript, or Python.

Complexity

  • TimeO(n)

    Each value is pushed once, poured once, and popped once across the whole run of commands.

  • SpaceO(n)

    The two stacks together hold every value that is still in the line.

Why you pour only when outbound is empty

Pouring while outbound still holds a value would place a newer arrival on top of an older one that has not been served. The line would reverse in the middle.

An empty pop

If both stacks are empty, there is no front. Record null and leave the stacks alone. Do not invent a zero.

Step by step on push 1, push 2, peek, pop

  1. 1

    push 1 lands on the inbound stack. Nothing is recorded but null, because a push does not serve a value.

  2. 2

    push 2 lands on top of 1. The inbound stack is 1, then 2. The outbound stack is still empty.

  3. 3

    peek finds the outbound stack empty, so the inbound values pour across. 2 moves first, then 1, so 1 is on top. The recorded front is 1.

  4. 4

    pop removes that same 1. The next serve would be 2. The results are [null, null, 1, 1].

Common mistakes

What mistakes do people make with queue?

  • Serving from the inbound stack

    The top of the inbound stack is the newest value. Popping it serves the last arrival first, which is a stack, not a queue.

    InsteadPushes go to inbound. Pops and peeks come from outbound, after a pour when outbound is empty.

  • Pouring on every command

    If outbound still has the oldest value and you pour again, the newer values land on top of it. The next pop returns the wrong item.

    InsteadPour only when outbound is empty. Leave a non-empty outbound stack untouched.

  • Skipping the result for an empty pop

    The output has one entry per command. Dropping the empty pop makes later results line up with the wrong commands.

    InsteadRecord null for a pop or peek when both stacks are empty. Record null for every push as well.

  • Using a stack for level order

    A stack hands back the neighbor you just discovered. That walk is depth-first. A level then runs in reverse, and the next level starts from the wrong node.

    InsteadEnqueue each new neighbor at the back, and dequeue from the front. Finish the current layer before the nodes you just added.

Practice it in Algofily

Which Algofily problems train queue?

1 problem is tagged Queue. The one tagged problem builds this queue out of two stacks.

A lock means the problem opens after you create an account. Pair With Target is open to try without one.

Start Learning.

Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.