Find the Winner of the Circular Game

medium queue simulation math

Problem

n friends 1..n stand in a circle. Starting from friend 1, count k around and that friend leaves; continue with the next remaining. Return the winner.

Inputn = 5, k = 2
Output3
Elimination order 2,4,1,5 leaves 3.

from collections import deque
def find_the_winner(n, k):
    q = deque(range(1, n + 1))
    while len(q) > 1:
        for _ in range(k - 1):
            q.append(q.popleft())
        q.popleft()
    return q[0]
function findTheWinner(n, k) {
  const q = [];
  for (let i = 1; i <= n; i++) q.push(i);
  let head = 0;
  while (q.length - head > 1) {
    for (let i = 0; i < k - 1; i++) { q.push(q[head++]); }
    head++;
  }
  return q[head];
}
class Solution {
    public int findTheWinner(int n, int k) {
        Deque<Integer> q = new ArrayDeque<>();
        for (int i = 1; i <= n; i++) q.add(i);
        while (q.size() > 1) {
            for (int i = 0; i < k - 1; i++) q.addLast(q.pollFirst());
            q.pollFirst();
        }
        return q.peek();
    }
}
int findTheWinner(int n, int k) {
    deque<int> q;
    for (int i = 1; i <= n; i++) q.push_back(i);
    while ((int)q.size() > 1) {
        for (int i = 0; i < k - 1; i++) { q.push_back(q.front()); q.pop_front(); }
        q.pop_front();
    }
    return q.front();
}
Time: O(n·k) Space: O(n)