Problem 385552 · hard · Phase 03 Linear Management & Searching

Pancake Flip Sequence

sorting · prefix reversal · constructive algorithm · checker

A stack of pancakes is given as a list sizes containing each integer from 1 to n exactly once (a permutation). The only move allowed is flip(k): reverse the order of the first k elements (1 <= k <= n).

Return a list of k values such that applying the flips in order leaves sizes sorted in ascending order. Any valid sequence of at most 2 * n flips is accepted; the empty list is valid when the input is already sorted.

Examples

Input:  sizes = [3, 2, 4, 1]
Output: [3, 4, 2, 3, 2]          (one of many valid answers)
Explanation: flip(3): [4, 2, 3, 1]; flip(4): [1, 3, 2, 4]; flip(2): [3, 1, 2, 4];
             flip(3): [2, 1, 3, 4]; flip(2): [1, 2, 3, 4].

Constraints

  • 0 <= n <= 500
  • Target complexity: O(n^2).

Goals

  • Sort with only one allowed operation: reversing a prefix
  • Move the largest unsorted element into place with at most two flips
  • Produce any valid sequence within a length bound
Starting Python…