Skip to content

950. Reveal Cards In Increasing Order 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  vector<int> deckRevealedIncreasing(vector<int>& deck) {
    ranges::sort(deck, greater<int>());

    deque<int> dq{deck[0]};

    for (int i = 1; i < deck.size(); ++i) {
      dq.push_front(dq.back());
      dq.pop_back();
      dq.push_front(deck[i]);
    }

    return {dq.begin(), dq.end()};
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int[] deckRevealedIncreasing(int[] deck) {
    final int n = deck.length;

    Arrays.sort(deck);

    Deque<Integer> dq = new ArrayDeque<>();
    dq.addFirst(deck[n - 1]);

    for (int i = n - 2; i >= 0; --i) {
      dq.addFirst(dq.getLast());
      dq.pollLast();
      dq.addFirst(deck[i]);
    }

    for (int i = 0; i < n; ++i)
      deck[i] = dq.pollFirst();

    return deck;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def deckRevealedIncreasing(self, deck: list[int]) -> list[int]:
    dq = collections.deque()

    for card in reversed(sorted(deck)):
      dq.rotate()
      dq.appendleft(card)

    return list(dq)