Ctrl K

Riffle Shuffles Until the Deck Resets

Medium
A deck holds an even number of cards, cards, labelled 0, 1, …, cards - 1 from top to bottom. One perfect shuffle works like this: split the deck exactly in half, then interleave the halves card by card: first card of the top half, first card of the bottom half, second card of the top half, second of the bottom half, and so on. For example, 0 1 2 3 becomes 0 2 1 3. Return how many shuffles (at least one) it takes until the deck is back in its original order for the first time.
Example 1
cards=6 → 4

0 1 2 3 4 5 → 0 3 1 4 2 5 → 0 4 3 2 1 5 → 0 2 4 1 3 5 → 0 1 2 3 4 5: four shuffles.

Example 2
cards=2 → 1

With two cards, the deck is 0 1 again right after the first shuffle.

Example 3
cards=8 → 3

A deck of 8 cards comes back to its starting order after 3 shuffles.

Constraints
  • 2 ≤ cards ≤ 1000
  • cards is even
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLast One in the Circle MediumRestore the Lost Dice MediumTop of the Digit Pyramid MediumRunning Sum Waves MediumWho Got Mentioned How Often Medium
loading Python…
Input
cards=6
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 40 tests on the server, hidden ones included.