Reveal Cards In Increasing Order

medium queue simulation sorting

Problem

You are given a deck of cards. The reveal procedure is: take the top card and reveal it, then move the next top card to the bottom of the deck; repeat until every card is revealed. Order the deck (return any such arrangement) so that the revealed cards come out in increasing order.

Inputdeck = [17, 13, 11, 2, 3, 5, 7]
Output[2, 13, 3, 11, 5, 17, 7]
Revealing top-to-bottom with the move-to-bottom rule yields 2, 3, 5, 7, 11, 13, 17 in increasing order.

from collections import deque

def deckRevealedIncreasing(deck):
    deck.sort()
    n = len(deck)
    q = deque(range(n))
    ans = [0] * n
    for x in deck:
        ans[q.popleft()] = x
        if q:
            q.append(q.popleft())
    return ans
function deckRevealedIncreasing(deck) {
  deck.sort((a, b) => a - b);
  const n = deck.length;
  const q = [];
  for (let i = 0; i < n; i++) q.push(i);
  const ans = new Array(n);
  for (const x of deck) {
    ans[q.shift()] = x;
    if (q.length) q.push(q.shift());
  }
  return ans;
}
class Solution {
    public int[] deckRevealedIncreasing(int[] deck) {
        Arrays.sort(deck);
        int n = deck.length;
        Deque<Integer> q = new ArrayDeque<>();
        for (int i = 0; i < n; i++) q.add(i);
        int[] ans = new int[n];
        for (int x : deck) {
            ans[q.poll()] = x;
            if (!q.isEmpty()) q.add(q.poll());
        }
        return ans;
    }
}
vector<int> deckRevealedIncreasing(vector<int>& deck) {
    sort(deck.begin(), deck.end());
    int n = deck.size();
    queue<int> q;
    for (int i = 0; i < n; i++) q.push(i);
    vector<int> ans(n);
    for (int x : deck) {
        ans[q.front()] = x; q.pop();
        if (!q.empty()) { q.push(q.front()); q.pop(); }
    }
    return ans;
}
Time: O(n log n) Space: O(n)