Reveal Cards In Increasing Order

MediumQueue · Simulation · Sorting🧩 Queue & Monotonic DequeLeetCode #950 ↗Updated

Problem

You hold a deck of cards with distinct values and may arrange it in any order. Cards are then revealed by repeating: take the top card and reveal it; if cards remain, move the new top card to the bottom. Return an ordering (top first) that makes the revealed values come out in increasing order.
Inputdeck=[17,13,11,2,3,5,7]Output[2,13,3,11,5,17,7]
Inputdeck=[1,1000]Output[1,1000]

1 ≤ n ≤ 1000  ·  1 ≤ deck[i] ≤ 106  ·  all values distinct

Try it yourself

Java
class Solution {
    public int[] deckRevealedIncreasing(int[] deck) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The reveal order of positions does not depend on the values. Simulate the process on indices 0..n-1 with a queue, and hand the sorted values to the positions in the order they get revealed.
PatternQueue & Monotonic Deque

Instinct Arrival order matters, or you need the max/min of a moving window - reach for a FIFO queue, or a deque of indices kept in sorted order.

Memory hack Old ones leave by the front door, weak ones get bounced out the back - so whoever stands at the front is always the champion.

Open the Queue & Monotonic Deque guide →

Approaches

Brute ForceUndo the Process with a List

Time O(n²)Space O(n)

Build the deck backwards, from the largest card to the smallest. Undoing one round means: move the bottom card back to the top, then put the card that was just revealed on top. With an ArrayList, inserting at the front shifts every element.

Java
public int[] deckRevealedIncreasing(int[] deck) {
    int[] sorted = deck.clone();
    Arrays.sort(sorted);
    List<Integer> pile = new ArrayList<>(); // index 0 = top
    for (int i = sorted.length - 1; i >= 0; i--) {
        if (!pile.isEmpty()) pile.add(0, pile.remove(pile.size() - 1)); // undo "top to bottom"
        pile.add(0, sorted[i]); // undo "reveal top"
    }
    int[] result = new int[deck.length];
    for (int i = 0; i < result.length; i++) result[i] = pile.get(i);
    return result;
}

Correct and intuitive, but each front insertion is O(n).

At a glance

LevelApproachTimeSpace
Brute ForceUndo the Process with a ListO(n²)O(n)
OptimalIndex Queue SimulationO(n log n)O(n)
Common pitfalls
  • Forgetting to sort first — the values must be handed out smallest first.
  • Moving a card to the bottom after the last reveal (empty queue).
  • Placing values by reveal step instead of by the polled position.
Interview tips
  • Notice that only positions matter, so simulate on indices, not values.
  • Trace the 7-card example to show which slot each sorted card lands in.
  • Mention that undoing the process backwards is an equivalent way to think about it.
Pattern
Queue simulation on indices → when a fixed shuffling rule decides where items end up, independent of their values.
My notes saved in this browser