Problem

You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].

You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.

You will do the following steps repeatedly until all cards are revealed:

  1. Take the top card of the deck, reveal it, and take it out of the deck.
  2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.
  3. If there are still unrevealed cards, go back to step 1. Otherwise, stop.

Return an ordering of the deck that would reveal the cards in increasing order.

Note that the first entry in the answer is considered to be the top of the deck.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Input: deck = [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation: 
We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom.  The deck is now [3,11,5,17,7,13].
We reveal 3, and move 11 to the bottom.  The deck is now [5,17,7,13,11].
We reveal 5, and move 17 to the bottom.  The deck is now [7,13,11,17].
We reveal 7, and move 13 to the bottom.  The deck is now [11,17,13].
We reveal 11, and move 17 to the bottom.  The deck is now [13,17].
We reveal 13, and move 17 to the bottom.  The deck is now [17].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.

Example 2

1
2
Input: deck = [1,1000]
Output: [1,1000]

Constraints

  • 1 <= deck.length <= 1000
  • 1 <= deck[i] <= 10^6
  • All the values of deck are unique.

Solution

Method 1 - Simulate in Reverse

Intuition

To reveal cards in increasing order, we can simulate the process in reverse: start from the largest card and reconstruct the deck backwards by always putting the next card on top, and if the deck is not empty, move the bottom card to the top.

Approach

Sort the deck. Starting from the largest, for each card, insert it at the front of a deque, and if the deque is not empty, move the last card to the front. This reconstructs the required order.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <vector>
#include <deque>
#include <algorithm>
using namespace std;
class Solution {
public:
    vector<int> deckRevealedIncreasing(vector<int>& deck) {
        sort(deck.begin(), deck.end());
        deque<int> dq;
        for (int i = deck.size() - 1; i >= 0; --i) {
            if (!dq.empty()) {
                dq.push_front(dq.back());
                dq.pop_back();
            }
            dq.push_front(deck[i]);
        }
        return vector<int>(dq.begin(), dq.end());
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import "sort"
func deckRevealedIncreasing(deck []int) []int {
    sort.Ints(deck)
    dq := []int{}
    for i := len(deck) - 1; i >= 0; i-- {
        if len(dq) > 0 {
            dq = append([]int{dq[len(dq)-1]}, dq[:len(dq)-1]...)
        }
        dq = append([]int{deck[i]}, dq...)
    }
    return dq
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import java.util.*;
class Solution {
    public int[] deckRevealedIncreasing(int[] deck) {
        Arrays.sort(deck);
        Deque<Integer> dq = new ArrayDeque<>();
        for (int i = deck.length - 1; i >= 0; i--) {
            if (!dq.isEmpty()) dq.addFirst(dq.removeLast());
            dq.addFirst(deck[i]);
        }
        int[] res = new int[deck.length];
        int idx = 0;
        for (int x : dq) res[idx++] = x;
        return res;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import java.util.*
class Solution {
    fun deckRevealedIncreasing(deck: IntArray): IntArray {
        deck.sort()
        val dq: Deque<Int> = ArrayDeque()
        for (i in deck.size - 1 downTo 0) {
            if (dq.isNotEmpty()) dq.addFirst(dq.removeLast())
            dq.addFirst(deck[i])
        }
        return dq.toIntArray()
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from collections import deque
class Solution:
    def deckRevealedIncreasing(self, deck: list[int]) -> list[int]:
        deck.sort()
        dq = deque()
        for card in reversed(deck):
            if dq:
                dq.appendleft(dq.pop())
            dq.appendleft(card)
        return list(dq)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
use std::collections::VecDeque;
impl Solution {
    pub fn deck_revealed_increasing(mut deck: Vec<i32>) -> Vec<i32> {
        deck.sort();
        let mut dq = VecDeque::new();
        for &card in deck.iter().rev() {
            if !dq.is_empty() {
                let last = dq.pop_back().unwrap();
                dq.push_front(last);
            }
            dq.push_front(card);
        }
        dq.into_iter().collect()
    }
}
1
2
3
4
5
6
7
8
9
function deckRevealedIncreasing(deck: number[]): number[] {
    deck.sort((a, b) => a - b);
    const dq: number[] = [];
    for (let i = deck.length - 1; i >= 0; i--) {
        if (dq.length > 0) dq.unshift(dq.pop()!);
        dq.unshift(deck[i]);
    }
    return dq;
}

Complexity

  • ⏰ Time complexity: O(n log n) — for sorting, and O(n) for simulation.
  • 🧺 Space complexity: O(n) — for the deque.