> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Reveal Cards In Increasing Order

Leetcode Problem 950: Reveal Cards In Increasing Order

Problem Summary

You have a deck of n cards with integer values. You reveal them one at a time using this process: reveal the top card, then move the next top card to the bottom of the deck, and repeat until all cards are revealed. Return an arrangement of the deck such that cards are revealed in increasing order.

Constraints:

  • The deck has between 1 and 1,000 cards.
  • All card values are distinct integers in the range [1, 1,000,000].

Techniques

  • Array
  • Queue
  • Sorting
  • Simulation

Solution

function deckRevealedIncreasing(deck: number[]): number[] {
    const deckSorted = deck.sort((a, b) => a - b)
    const neededPositions: number[] = []

    while (deckSorted.length > 0) {
        const nextElement = deckSorted.pop()!

        if (neededPositions.length > 0) {
            neededPositions.unshift(neededPositions.pop()!)
        }

        neededPositions.unshift(nextElement)
    }

    return neededPositions
}

console.log(deckRevealedIncreasing([17,13,11,2,3,5,7]))
console.log(deckRevealedIncreasing([1,1000]))