Gamified challenge · Greedy placement
stack[0] is the size of the top pancake and stack[n − 1] the bottom one. A flip `k` slides the spatula under the k-th pancake from the top and turns the top k over, reversing their order: flip 3 on [3, 2, 4, 1] gives [4, 2, 3, 1].
Write flips(stack) that returns a list of flip sizes (each from 1 to n) that leaves the stack sorted smallest on top (each pancake no bigger than the one below it), using at most `2n` flips. Any such list is accepted; an already sorted stack can return [].
For [3, 2, 4, 1], one answer is [3, 4, 2, 3, 2]: [4, 2, 3, 1] → [1, 3, 2, 4] → [3, 1, 2, 4] → [2, 1, 3, 4] → [1, 2, 3, 4].
This game is part of the paid plans. Sign in, then pick a plan to write your answer, watch it play out, and step through the algorithm with its guide.
Sign in with Google