Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

A queue: first in, first out

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.