1816. Fewest Pancake Flips
A cook has a stack of n pancakes of distinct sizes, given in pancakes from the top of the stack to the bottom; the values are a permutation of 1..n. The only tool is a spatula: choose a number k and slide it under the top k pancakes, then flip them all at once, which reverses the order of the first k entries.
Return the minimum number of flips needed so that the stack ends up with the smallest pancake on top and the sizes increasing towards the bottom, that is 1, 2, ..., n. If the stack is already sorted the answer is 0. Searching all n! arrangements breadth-first is too slow for n = 10. A depth-limited search that deepens its limit step by step, and abandons a branch when the flips used plus the number of adjacent pairs differing by more than one (counting a virtual pancake of size n + 1 under the stack) exceeds the limit, finishes quickly, with O(n) memory and time well below n!.
Example 1
- Input:
- pancakes = [2,1,3]
- Output:
- 1
- Explanation:
Reversing the first two pancakes gives 1, 2, 3 in a single flip.
Example 2
- Input:
- pancakes = [3,1,2]
- Output:
- 2
- Explanation:
Flip the top 3 to get 2, 1, 3 and then flip the top 2 to get 1, 2, 3, so 2 flips are needed.
Example 3
- Input:
- pancakes = [1,2,3,4]
- Output:
- 0
- Explanation:
The stack is already sorted from smallest on top, so no flips are needed.
Constraints
1 ≤ n ≤ 10
pancakes is a permutation of 1..n
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms
Expected complexity
- Time
- O(b^d * n) with gap pruning (fast for n <= 10)
- Space
- O(n)