101 Logo
onenoughtone

Problem Statement

Pancake Sorting

You're given an array of integers, and you need to sort it using a special operation called a "pancake flip".

In one pancake flip, you do the following steps:

  • Choose an integer k where 1 ≤ k ≤ array.length.
  • Reverse the order of the first k elements of the array.

For example, if the array is [3, 2, 1, 4] and you perform a pancake flip with k = 3, you reverse the sub-array [3, 2, 1], resulting in the array [1, 2, 3, 4].

Your task is to return an array of the k-values corresponding to a sequence of pancake flips that sort the array. Any valid answer that sorts the array within 10 * array.length flips will be accepted.

Examples

Example 1:

Input: [3,2,4,1]
Output: [4,2,4,3]
Explanation: We perform 4 pancake flips, with k values 4, 2, 4, and 3. Starting state: A = [3, 2, 4, 1] After 1st flip (k=4): A = [1, 4, 2, 3] After 2nd flip (k=2): A = [4, 1, 2, 3] After 3rd flip (k=4): A = [3, 2, 1, 4] After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted.

Example 2:

Input: [1,2,3]
Output: []
Explanation: The input is already sorted, so there is no need to flip anything. Note that other answers, such as [3, 3], would also be accepted.

Constraints

  • 1 <= arr.length <= 100
  • 1 <= arr[i] <= arr.length
  • All integers in arr are unique (i.e., arr is a permutation of the integers from 1 to arr.length)

Problem Breakdown

To solve this problem, we need to:

  1. The key insight is to sort the array one element at a time, starting from the largest element
  2. For each step, find the position of the largest unsorted element, then use two flips to move it to its correct position
  3. The first flip brings the largest element to the beginning of the array, and the second flip moves it to its correct position at the end
  4. This approach guarantees that the array will be sorted in at most 2n flips, where n is the length of the array
  5. The problem allows for multiple valid solutions, as long as the array is sorted within the specified number of flips
ProblemSolutionCode
101 Logo
onenoughtone