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.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.
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.
stack=[1, 2, 3] → []
The stack is already in order, so no flips are needed.
stack is a permutation of the numbers 1 to len(stack)stack=[2, 3, 1]
[2, 3]
Run checks the first 3 tests in your browser. Submit checks all 100 tests on the server, hidden ones included.