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,2,4,3]
💡 Note: Flip k=4: [3,2,1,4] → [4,1,2,3]. Flip k=2: [4,1,2,3] → [1,4,2,3]. Flip k=4: [1,4,2,3] → [3,2,4,1]. Flip k=3: [3,2,4,1] → [4,2,3,1]. Continue until sorted.
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,3,2]
💡 Note: Flip k=4: [4,3,2,1] → [1,2,3,4]. But greedy approach: flip k=4 to move 4 to position 0, then flip k=4 to put it at end, then work on [3,2,1]

Constraints

  • 1 ≤ arr.length ≤ 10
  • 1 ≤ arr[i] ≤ arr.length
  • All integers in arr are unique

Visualization

Tap to expand
Pancake Sorting: Sort Array Using Flip OperationsInput Array3214Pancake Flip k=3: Reverse first 3 elementsAfter Flip1234Final Sorted1234Output: Sequence of flip positions [k-values]Goal: Find any valid sequence that sorts the array in ≤ 10n flips
Understanding the Visualization
1
Input Array
Unsorted array [3,2,1,4] with pancake flip operations available
2
Flip Operations
Can flip prefix of any length k, reversing elements arr[0...k-1]
3
Sorted Output
Return sequence of k-values that sorts the array
Key Takeaway
🎯 Key Insight: Use a greedy strategy to systematically move the largest unsorted element to its correct position with at most 2 flips per element
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