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:

  1. Choose an integer k where 1 <= k <= arr.length
  2. 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
Pancake Sorting Algorithm INPUT Array as Pancake Stack 3 2 1 4 Input Array: arr = [3, 2, 1, 4] indices: 0 1 2 3 ALGORITHM STEPS 1 Find max (4) at idx 3 Flip k=4: [4,1,2,3] 2 Move 3 to position Flip k=2: [1,4,2,3] 3 Find max in unsorted Flip k=4: [3,2,4,1] 4 Final arrangement Flip k=3: [1,2,3,4] Greedy Strategy: Flip reverses top k pancakes k-values sequence: [4, 2, 4, 3] FINAL RESULT Sorted Pancake Stack 1 2 3 4 Output (k-values): [4, 2, 4, 3] SORTED - OK Key Insight: The greedy approach works by repeatedly finding the largest unsorted element and moving it to its correct position. Each element requires at most 2 flips: one to bring it to top, one to flip it to its final position. Time Complexity: O(n^2) | Maximum flips needed: 2n (well within 10*n limit) TutorialsPoint - Pancake Sorting | Greedy - Move Largest Element First
Asked in
Google 25 Amazon 18 Facebook 15 Microsoft 12
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen