Problem 258418 · medium · Phase 02 Linear Data Structures

Counting Out With Reversal

queues · deque · simulation

n children numbered 1 to n stand in a circle in clockwise order. A counting-out game removes one child per round:

  • Round 1 starts counting at child 1 and goes clockwise: the k-th child counted (child 1 counts as 1) is removed.
  • After each removal the direction reverses, and the next round starts counting from the child who is adjacent to the removed one in the new direction.

Return the list of children in the order they are removed (all n of them).

Examples

Input:  n = 5, k = 2
Output: [2, 5, 3, 4, 1]
Explanation: clockwise from 1: 1, 2 -> remove 2. Counter-clockwise from 1: 1, 5 -> remove 5.
             Clockwise from 1: 1, 3 -> remove 3. Counter-clockwise from 1: 1, 4 -> remove 4. Then 1.

Input:  n = 4, k = 1
Output: [1, 4, 2, 3]

Constraints

  • 1 <= n <= 5000
  • 1 <= k <= 10**9
  • Target: O(n * min(k, n)) with rotation, or O(n) per round using deque.rotate with a modulo

Goals

  • Use both ends of a deque to count in either direction
  • Alternate the direction of rotation each round
Starting Python…