DSA Factory
Free Stacks and queues lessonsStacks and queues · Stage 3 · Queues and deques · Step 3

Order the deck

Arrange a deck so that dealing it by a fixed rule shows the cards in increasing order, by simulating the rule on positions instead of cards. About 16 minutes.

Work backwards with positions

A dealer follows a rule: reveal the top card, then move the next top card to the bottom, and repeat. You want the revealed cards to come out in increasing order. Which arrangement of the deck makes that happen?

The rule moves places, not values. Use a queue of place numbers 0 to n minus 1, and run the rule on it. The first place revealed must hold the smallest card.

Queue of places: not cards.
Revealed place: gets the next smallest card.
In code
from collections import deque
q = deque(range(5))     # 0, 1, 2, 3, 4
spot = q.popleft()      # 0
Deck 17, 13, 11, 2, 3, 5, 7 sorted is 2, 3, 5, 7, 11, 13, 17. Places are 0 to 6.
0
0
1
1
2
2
3
3
4
4
5
5
6
6
i

Reveal place 0: it gets 2. Place 1 moves to the back. Queue: 2, 3, 4, 5, 6, 1.

Move 1 of 7

Then move one to the back

After revealing a place, the rule says to move the next top card to the bottom. On the queue, that means taking the new front place off and adding it to the back.

If the queue is empty after a reveal, there is nothing left to move, so check before moving. When the sorted cards run out, every place has been filled, and the result is the arrangement.

Front place: moves to the back after each reveal.
Check the queue: before moving the front.
In code
q.append(q.popleft())   # to the back
Quick check

Why can we run the rule on place numbers instead of on the actual cards?

  1. AThe rule only moves places around and never looks at card values
  2. BThe deck is already sorted
  3. CCards are slower to move than numbers
Show the answer

The rule only moves places around and never looks at card values. So the order in which places are revealed is the same for every deck of that size.

Your problem

Reveal cards in increasing order

You are given an integer array deck with distinct values. You may arrange the deck in any order, and then it is dealt like this: reveal the top card and take it away, then move the next top card to the bottom of the deck, and repeat until all cards are revealed. Return the arrangement (top card first) for which the revealed cards come out in increasing order.

Example
deck = [17, 13, 11, 2, 3, 5, 7] → [2, 13, 3, 11, 5, 17, 7]

1 ≤ length of deck ≤ 100,000 · 1 ≤ deck[i] ≤ 1,000,000 · all values are different

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve