Ctrl K

A Stack of Pancakes and a Spatula

Medium
A cook holds a stack of n pancakes of distinct sizes: stack[0] is the top one, and the sizes are the numbers 1 to n. The only move available is to slide the spatula under the k-th pancake from the top and flip the top k pancakes at once, reversing their order. The goal is a stack that reads 1, 2, …, n from top to bottom. The cook follows a fixed rule: for size from n down to 2 - if pancake size is already in its spot (position size - 1 from the top), do nothing; - otherwise, if pancake size is not on top, flip the stack down to and including it so it comes to the top; - then flip the top size pancakes, which puts pancake size in place. Return the list of k values of all flips, in the order the cook makes them.
Example 1
stack=[2, 3, 1] → [2, 3]

The largest pancake, 3, is second: flip 2 gives [3, 2, 1], flip 3 gives [1, 2, 3]. Pancake 2 is then already in place.

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

Pancake 4 is already on top, so flip 4 right away: [3, 2, 1, 4]. Then 3 is on top, flip 3, and the stack is sorted.

Example 3
stack=[1, 2, 3] → []

The stack is already in order, so no flips are needed.

Constraints
  • 1 ≤ len(stack) ≤ 100
  • stack is a permutation of the numbers 1 to len(stack)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStudios for Recording Sessions MediumFix the Middle of the Line MediumStick Triples That Form a Triangle MediumBest-Paid Gig for Each Worker MediumLining Up Against Rivals Medium
loading Python…
Input
stack=[2, 3, 1]
Expected
[2, 3]

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