Skip to content
BytePatterns

Pancake Flips to Sort

MediumSorting#selection-sort#prefix-reversal~25m

Problem

A robot arm can only do one move on a stack of numbered plates: slide a spatula under the top k plates and flip them over, which reverses the first k values of the list. Given a list arr that is a permutation of 1 to n, return a list of flip sizes k that leaves arr in ascending order. Any answer with at most 2n flips is accepted; the examples show the answer from placing the largest unplaced value first. The list has up to 100 values.

Examples

Input:  arr = [3, 2, 4, 1]
Output: [3, 4, 2, 3, 2]
Why:    flip 3 brings 4 to the front, flip 4 sends it to the end, and so on
Input:  arr = [2, 1]
Output: [2]
Input:  arr = [1, 2, 3]
Output: []
Why:    edge case, already sorted, so no flip is needed

Hints

0 / 3

Stuck on the idea rather than the code? Selection Sort covers it.