Data Structures & AlgorithmsHardProduct Company SDE pattern

What is printed? (queue simulation – hot potato with step k)

What is printed? (queue simulation – hot potato with step k)
from collections import deque
q = deque(range(1, 8)); out = []
while len(q) > 1:
    q.rotate(-2)
    out.append(q.popleft())
print(out, q[0])
  1. A. [3, 6, 2, 7, 5, 1] 3
  2. B. [2, 4, 6, 1, 5, 3] 7
  3. C. [3, 6, 1, 5, 2, 7] 4
  4. D. [3, 6, 2, 7, 5, 1] 4

Correct answer: D. [3, 6, 2, 7, 5, 1] 4

Each round passes the potato twice (rotate left by 2) and eliminates the person now at the front – the Josephus problem with every 3rd person removed. For n = 7, k = 3 the survivor is 4. The deque gives O(k) per elimination.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic