Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: A magician reveals cards like this: show the top card, then move the next top card to the bottom; repeat. Arrange the deck so the cards are revealed in increasing order (simulate with a deque of positions).

Problem: A magician reveals cards like this: show the top card, then move the next top card to the bottom; repeat. Arrange the deck so the cards are revealed in increasing order (simulate with a deque of positions).
from collections import deque
def reveal_order(cards):
    idx = deque(range(len(cards))); res = [0] * len(cards)
    for c in sorted(cards):
        res[idx.popleft()] = c
        if idx: idx.append(idx.popleft())
    return res
print(reveal_order([5, 1, 9, 3, 7, 2]))
What is printed?
  1. A. [1, 2, 3, 5, 7, 9]
  2. B. [1, 3, 7, 2, 5, 9]
  3. C. [1, 5, 2, 9, 3, 7]
  4. D. [1, 7, 2, 9, 3, 5]

Correct answer: C. [1, 5, 2, 9, 3, 7]

Run the reveal process on deck POSITIONS: the first position revealed gets the smallest card, the next revealed position the next smallest, and so on. Positions are revealed in the order 0, 2, 4, 1, 5, 3, so 1→0, 2→2, 3→4, 5→1, 7→5, 9→3: [1, 5, 2, 9, 3, 7]. Playing that deck reveals 1, 2, 3, 5, 7, 9. O(n log n) for the sort.

More Coding Interview Problems questions

Exams that ask this topic