Reveal Cards In Increasing Order - Problem

Imagine you have a deck of cards with unique numbers, and you want to arrange them in a special way. You'll follow a specific reveal pattern:

  1. Reveal the top card (remove it)
  2. Move the next top card to the bottom
  3. Repeat until all cards are revealed

Your goal is to arrange the initial deck such that when you follow this reveal pattern, the cards come out in increasing numerical order.

Example: If you want cards to be revealed as [2, 3, 5, 7], you need to figure out how to initially arrange the deck [2, 5, 3, 7] so that the reveal process produces the desired sequence.

Given an array deck representing the cards, return the initial arrangement that will reveal the cards in sorted order.

Input & Output

example_1.py โ€” Basic Case
$ Input: deck = [17,13,11,2,3,5,7]
โ€บ Output: [2,13,3,11,5,17,7]
๐Ÿ’ก Note: When we follow the reveal pattern with this arrangement, we get [2,3,5,7,11,13,17] in increasing order. The algorithm sorts the input and uses reverse simulation to find the required initial arrangement.
example_2.py โ€” Small Case
$ Input: deck = [1,2,3,4]
โ€บ Output: [1,3,2,4]
๐Ÿ’ก Note: Starting with [1,3,2,4]: reveal 1, move 3 to bottom โ†’ [2,4,3]; reveal 2, move 4 to bottom โ†’ [3,4]; reveal 3, move 4 to bottom โ†’ [4]; reveal 4. Final sequence: [1,2,3,4] โœ“
example_3.py โ€” Edge Case
$ Input: deck = [1]
โ€บ Output: [1]
๐Ÿ’ก Note: With only one card, no rearrangement is needed. The single card is revealed immediately, maintaining the sorted order.

Constraints

  • 1 โ‰ค deck.length โ‰ค 1000
  • 1 โ‰ค deck[i] โ‰ค 106
  • All values in deck are unique
  • The deck array represents cards with distinct integer values

Visualization

Tap to expand
๐ŸŽญ The Card Reveal Magic Trick๐Ÿ˜ŠMagicianOriginal Deck (Random Order):1713112โœจTarget Reveal (Sorted):2357๐Ÿ”„ Reveal Pattern:1. Reveal Topโ†’2. Move to Bottomโ†’3. Repeatโšก Reverse Engineering:Work backwards from [2,3,5,7] to find initial arrangementProcess: 7 โ†’ 5 โ†’ 3 โ†’ 2For each: Move bottom to top, then add card to top๐ŸŽฏ Magic Initial Arrangement:2537โœจ This arrangement reveals [2,3,5,7] using the pattern!
Understanding the Visualization
1
Setup the Target
Sort cards to know the desired reveal sequence: [2,3,5,7]
2
Work Backwards
Process cards from largest (7) to smallest (2)
3
Reverse the Magic
For each card: move bottom to top, then place card on top
4
Perfect Arrangement
The result [2,5,3,7] will reveal cards in sorted order!
Key Takeaway
๐ŸŽฏ Key Insight: Instead of trying all arrangements, reverse the reveal process to directly construct the solution. Work backwards from the target sequence using queue operations!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
52.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen