DSA Factory
Free lessonsStacks and queues · Stage 0 · Last in, first out · Step 4

A queue: first in, first out

Join at the back, leave from the front. About 10 minutes.

Think of the line at a canteen counter. People join at the back and are served from the front. Whoever came first leaves first, which is what makes a queue fair.

A queue has two moves: add at the back, and take from the front. Never the other way round.

Add at the back: new arrivals join the end of the line.
Take from the front: the one who waited longest leaves first.
In code
from collections import deque

line = deque(players)
while len(line) > 1:
    line.append(line.popleft())
    line.popleft()
return line[0]
Pass and leave with players [1, 2, 3, 4, 5]
1
0
2
1
3
2
4
3
5
4
front

1 is at the front and walks to the back. Then 2 is at the front and leaves. Line: [3, 4, 5, 1].

Move 1 of 4

Don't take from the front of a plain list

In Python, removing the first item of a list, in JavaScript shift, and erasing the first item of a C++ vector all make every other item step one place to the left, like a whole queue shuffling forward each time one person leaves.

Use a real queue instead: deque in Python, queue in C++, and ArrayDeque in Java. In JavaScript, keep an array and a head index that marks the front, and move the index forward instead of removing.

Removing from the front of a list: moves every other item.
Deque, queue, ArrayDeque: both ends work in about one step.
JavaScript: an array plus a head index.
Quick check

What does the line look like after one round?

line = [6, 2, 8], front first. The front walks to the back, then the new front leaves.
  1. A[8, 6]
  2. B[2, 8]
  3. C[6, 8]
Show the answer

[8, 6]. 6 walks to the back: [2, 8, 6]. Then 2 leaves: [8, 6].

Your problem

Pass and leave

Players stand in a line. players[0] is at the front. Until only one player is left, repeat two moves: the player at the front walks to the back of the line, and then the player now at the front leaves the game. Return the number of the last player left.

Example
players = [1, 2, 3, 4, 5] → 3

1 ≤ n ≤ 1,000,000 · 0 ≤ each number ≤ 2,000,000,000 · the numbers are all different

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding