QueueMedium

Reveal Cards Visualizer

What is Reveal Cards

Cards are in a deck. Reveal the top card, then move the new top card to the bottom. Repeat. Return the order the cards are revealed. The input is the deck you start with; any order of those values is allowed, and the answer is the revealed order of the sorted deck under this process.

Approach

Put the indexes 0..n-1 in a queue. For each card from small to large, write it at the front index, then move the next index to the rear.

Visualization & algorithm

Indexes waiting, and the deck being filled
sort the cards
queue = indexes 0..n-1
for each card from small to large:
write it at the front index
move the next index to the rear
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n log n)Sorting dominates. The queue pass is linear.
SpaceO(n)The index queue and the answer.

Implementation

from collections import deque
def solve(self, deck):
    deck = sorted(deck)
    q = deque(range(len(deck)))
    ans = [0]*len(deck)
    for card in deck:
        ans[q.popleft()] = card
        if q: q.append(q.popleft())
    return ans