AlgoInsight

DSA problem

Reveal Cards In Increasing Order

MediumQueuesPattern: Queuestop300AmazonGoogleMicrosoftBloomberg

You are given an integer array deck where deck[i] is the value of the i-th card. You must reorder the cards so that the following procedure reveals every card in strictly increasing order: while the deck is non-empty, take the top card and reveal it, then if at least one card remains, take the next top card and move it to the bottom. Return the deck arrangement that achieves this.

The challenge is to invert the reveal-and-rotate process: given the sorted output, recover the input. A brute-force search would be exponential, but a clean simulation handles the problem in linear time.

The optimal approach uses a deque of positions 0..n-1 and walks the deck in sorted order. For each next smallest card value, take the front index of the deque and assign that card value to the result at that position; then, if the deque is not empty, move the new front index to the back. This exactly reverses the reveal-and-rotate sequence: the front of the deque corresponds to the next slot that will be revealed, and the next slot that will be revealed only after a rotation gets moved to the back so it is processed later.

Because each index enters the deque once and is touched a constant number of times, the algorithm runs in O(n log n) time (dominated by the initial sort) and uses O(n) extra space. It is also a fantastic exercise in thinking with a deque: front pops, back pushes, and how rotation can be modeled by a single pop-then-push.

Examples

Example 1
Input: deck = [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation: Simulating the reveal procedure on [2,13,3,11,5,17,7]: reveal 2, move 13 to bottom → [3,11,5,17,7,13]; reveal 3, move 11 → [5,17,7,13,11]; reveal 5, move 17 → [7,13,11,17]; reveal 7, move 13 → [11,17,13]; reveal 11, move 17 → [13,17]; reveal 13, move 17 → [17]; reveal 17. The revealed sequence is 2,3,5,7,11,13,17 — sorted.
Example 2
Input: deck = [1,1000]
Output: [1,1000]
Explanation: For only two cards, reveal the smaller first and the larger after one rotation — already sorted ordering [1, 1000] works.
Example 3
Input: deck = [1,2,3]
Output: [1,3,2]
Explanation: Reveal 1, move 3 to bottom → [2,3]; reveal 2, move 3 to bottom → [3]; reveal 3. Order is 1,2,3.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

queuedequesortingsimulation

Browse all DSA problems