Ctrl K

Deal Out From the Lowest Card

Hard
A deck holds cards with distinct integers, from top to bottom cards[0], cards[1], … While the deck is not empty, one move is made: - if the top card is the smallest of the cards still in the deck, it is removed; - otherwise it is moved to the very bottom of the deck. How many moves does it take to empty the deck? Simulating directly can take on the order of n² moves; try to count the answer faster.
Example 1
cards=[5, 2, 7] → 5

5 is not the smallest, so it goes to the bottom: [2, 7, 5]. Remove 2: [7, 5]. 7 goes to the bottom: [5, 7]. Remove 5, then 7. Five moves in total.

Example 2
cards=[3, 1, 2] → 4

One move sends 3 to the bottom, then 1, 2 and 3 come off one by one: 1 + 3 = 4.

Example 3
cards=[-4, 0, 9] → 3

The deck is already in increasing order, so every top card is removed right away.

Constraints
  • 1 ≤ len(cards) ≤ 10⁵
  • -10⁹ ≤ cards[i] ≤ 10⁹
  • all numbers in cards are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSmaller Values to the Right HardWindow Sums Within a Band HardPairs With a Steep Drop HardCost of Filling a Sorted Shelf HardTriples Both Rankings Agree On Hard
loading Python…
Input
cards=[5, 2, 7]
Expected
5

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