Don Chuy's pancakes
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- loops
- lists
- indexes
Problem
On Sundays at Don Chuy's diner the pancakes come out crooked: they get stacked however they land. Don Chuy sorts them with nothing but his spatula, biggest at the bottom and smallest on top, always the same way, and his granddaughter counts the flips to see if he beat last Sunday. You get stack, the sizes from top to bottom (positive whole numbers, all different; it may be empty). Flipping k means reversing the first k of the list. For m from the length down to 2, one at a time, find the biggest among the first m, at position i. If i is m - 1, it is already in place and he does nothing. Otherwise, first, only if i is not 0, he flips i + 1 to bring it to the top; then he flips m to send it down to its place. Return how many flips he made. With [2, 4, 1, 3]: with m 4, the 4 is at 1, he flips 2 ([4, 2, 1, 3]) and flips 4 ([3, 1, 2, 4]); with m 3, the 3 is already on top so he only flips 3 ([2, 1, 3, 4]); with m 2 he flips 2. You return 4. Empty, a single one or already sorted, it is 0.
Examples
The example
[2, 4, 1, 3] → 4
The biggest is already on top
[3, 1, 2] → 2
Upside down, a single flip
[4, 3, 2, 1] → 1
Already sorted
[1, 2, 3, 4] → 0
A stack of five
[5, 1, 4, 2, 3] → 6
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def count_flips(stack):
passJavaScript
function countFlips(stack) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.