Pancake Sorting - Problem
Given an array of integers arr, sort the array by performing a series of pancake flips.
In one pancake flip we do the following steps:
- Choose an integer
kwhere1 <= k <= arr.length - Reverse the sub-array
arr[0...k-1](0-indexed)
For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.
Return an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [3,2,1,4]
›
Output:
[4,4,3]
💡 Note:
Use greedy approach: move largest element 4 to front with flip k=4 giving [4,1,2,3], then flip k=4 to put it at end giving [3,2,1,4]. Next move 3 to front with flip k=3 giving [1,2,3,4], which completes the sorting.
Example 2 — Already Sorted
$
Input:
arr = [1,2,3,4]
›
Output:
[]
💡 Note:
Array is already sorted, no flips needed
Example 3 — Reverse Order
$
Input:
arr = [4,3,2,1]
›
Output:
[4]
💡 Note:
Max element 4 is at position 0, so flip k=4 to reverse entire array: [4,3,2,1] → [1,2,3,4]
Constraints
- 1 ≤ arr.length ≤ 10
- 1 ≤ arr[i] ≤ arr.length
- All integers in arr are unique
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code