Pancake Sorting
Problem
Given an array of integers arr, return a sequence of pancake flips that sorts the array in ascending order, where a pancake flip reverses the order of the first k elements for some k.
- 1 ≤ arr.length ≤ 100
- 1 ≤ arr[i] ≤ arr.length
- All integers in arr are unique
Example
arr = [3,2,4,1][4,2,4,3]The algorithm sorts the array by repeatedly placing the largest unsorted element at its correct position. For the input [3,2,4,1], the largest element in the full array is 4 at index 2. First, flip the first 3 elements to bring 4 to the front: arr becomes [4,2,3,1]. Then flip the first 4 elements to move 4 to its final position: arr becomes [1,3,2,4]. Next, consider the first 3 elements [1,3,2]. The largest is 3 at index 1. Flip first 2 elements: arr becomes [3,1,2,4]. Flip first 3 elements: arr becomes [2,1,3,4]. Finally, sort the first 2 elements by flipping first 2 elements: arr becomes [1,2,3,4]. The sequence of flips is [3,4,2,3,2]. The output [4,2,4,3] is another valid sequence that achieves sorting.
Approach
Straightforward Solution
A brute-force approach would try all possible sequences of flips, which is combinatorially explosive and infeasible for arrays of even moderate size.
Core Observation
Each pancake flip reverses a prefix of the array, which can be used to move the largest unsorted element to its correct position by at most two flips: first flip to bring it to the front, second flip to move it to its final position.
Path to Optimal
The key insight is to sort the array from the largest element down to the smallest by repeatedly placing the largest unsorted element at its correct position. For each size from n down to 2, find the index of the largest element in the unsorted prefix. If it is not already at the end of the prefix, flip it to the front (if not already there), then flip the entire prefix to move it to its correct position. This greedy approach guarantees sorting in O(n) flips.
Optimal Approach
Iterate from the full array size down to 2. For each size, find the max element's index in the prefix. If max is not at the end, flip the prefix up to max to bring it to front, then flip the prefix up to size to move it to its final position. Record each flip size. This approach sorts the array in at most 2n flips and runs in O(n^2) time due to scanning for max each iteration.
Time
O(n^2)
For each size from n down to 2, the algorithm scans the prefix to find the max element (O(n)) and performs up to two flips (each O(k) but bounded by n). This results in O(n^2) time overall.
Space
O(n)
The flips list stores up to 2n flip sizes, which is O(n) auxiliary space. The input array is modified in place, so no additional significant space is used.
Pattern Spotlight
Greedy Algorithms (Greedy Placement via Reversal)
The optimal pancake sorting strategy greedily places the largest unsorted element at its correct position by at most two prefix reversals, reducing the problem size step-by-step until fully sorted.
Solution
| 1 | class Solution: |
| 2 | def pancakeSort(self, arr: list[int]) -> list[int]: |
| 3 | flips = [] |
| 4 | |
| 5 | def flip(end): |
| 6 | left = 0 |
| 7 | right = end |
| 8 | |
| 9 | while left < right: |
| 10 | arr[left], arr[right] = arr[right], arr[left] |
| 11 | left += 1 |
| 12 | right -= 1 |
| 13 | |
| 14 | for size in range(len(arr), 1, -1): |
| 15 | max_index = 0 |
| 16 | |
| 17 | for i in range(1, size): |
| 18 | if arr[i] > arr[max_index]: |
| 19 | max_index = i |
| 20 | |
| 21 | if max_index == size - 1: |
| 22 | continue |
| 23 | |
| 24 | if max_index != 0: |
| 25 | flip(max_index) |
| 26 | flips.append(max_index + 1) |
| 27 | |
| 28 | flip(size - 1) |
| 29 | flips.append(size) |
| 30 | |
| 31 | return flips |
Step-by-Step Solution
Accumulate Flip Operations and Define Prefix Reversal
| 3 | flips = [] |
| 5 | def flip(end): |
| 6 | left = 0 |
| 7 | right = end |
| 9 | while left < right: |
| 10 | arr[left], arr[right] = arr[right], arr[left] |
| 11 | left += 1 |
| 12 | right -= 1 |
Objective
To maintain a list of flip sizes and implement a helper function that reverses the prefix of the array up to a given index.
Key Insight
Recording flip sizes is essential to return the sequence of operations. The flip function reverses the prefix in place by swapping elements from the ends inward, enabling the core operation of pancake sorting. This abstraction cleanly separates the reversal logic from the sorting logic, improving clarity and correctness.
Interview Quick-Check
Core Logic
The flip function reverses the prefix of the array in place by swapping elements symmetrically from the start to the given end index.
State & Boundaries
The flips list records the sizes of each prefix reversal performed, which is the required output.
Common Pitfalls & Bugs
Forgetting to increment and decrement pointers correctly in the flip function can cause infinite loops or incorrect reversals.
Iteratively Place Largest Unsorted Element via Greedy Flips
| 14 | for size in range(len(arr), 1, -1): |
| 15 | max_index = 0 |
| 17 | for i in range(1, size): |
| 18 | if arr[i] > arr[max_index]: |
| 19 | max_index = i |
| 21 | if max_index == size - 1: |
| 22 | continue |
| 24 | if max_index != 0: |
| 25 | flip(max_index) |
| 26 | flips.append(max_index + 1) |
| 28 | flip(size - 1) |
| 29 | flips.append(size) |
Objective
To sort the array by repeatedly locating the largest unsorted element and moving it to its correct position using at most two flips.
Key Insight
By scanning the unsorted prefix to find the largest element, the algorithm ensures that each iteration places one element in its final position. If the largest element is not already at the end, flipping it to the front and then flipping the entire prefix moves it to the correct position. This greedy approach reduces the problem size by one each iteration and guarantees sorting in O(n^2) time with at most 2n flips.
Interview Quick-Check
Core Logic
For each prefix size from n down to 2, find the max element's index; if not at the end, flip it to front (if needed), then flip the entire prefix to place it correctly.
State & Boundaries
Skip flipping if the max element is already at the end of the current prefix to avoid unnecessary operations.
Common Pitfalls & Bugs
Failing to append the correct flip sizes (max_index + 1 and size) to the flips list leads to incorrect output.
Complexity
The nested loops and prefix reversals result in O(n^2) time complexity, which is acceptable given the problem constraints.
Return the Sequence of Flip Sizes
| 31 | return flips |
Objective
To output the recorded sequence of flips that sorts the array.
Key Insight
Returning the flips list completes the algorithm by providing the required sequence of prefix reversal sizes. This output can be used to verify the correctness of the sorting process or to reproduce the sorting steps.
Interview Quick-Check
Core Logic
Returning the flips list provides the exact sequence of prefix reversals that sorts the input array.
Line Analysis
This solution has 3 Critical lines interviewers watch for.
arr[left], arr[right] = arr[right], arr[left]
Swap elements at left and right pointers.
This line is the core reversal operation; swapping elements at the pointers progressively reverses the prefix in place, which is essential for the pancake flip.
if max_index != 0:
Flip the prefix up to max_index to bring the largest element to the front.
This flip is critical because it brings the largest unsorted element to the front, enabling the subsequent flip to place it correctly at the end of the prefix.
flips.append(max_index + 1)
Flip the entire prefix to move the largest element to its correct position.
This flip finalizes the placement of the largest element by reversing the entire prefix, moving it from the front to its sorted position.
for i in range(1, size):
Scan the current prefix to find the index of the largest element.
Identifying the largest element in the unsorted prefix is critical to the greedy strategy of placing it correctly with flips.
if arr[i] > arr[max_index]:
Compare current element with the current max to update max_index.
Updating max_index ensures the algorithm always knows the position of the largest element found so far in the prefix.
max_index = i
Assign new max_index when a larger element is found.
This update maintains the correct index of the largest element, which guides the flip operations.
return flips
Return the list of flip sizes that sorts the array.
Returning the flips list provides the required output representing the sequence of pancake flips that sort the input array.
while left < right:
Loop while left pointer is less than right pointer to swap elements.
Swapping elements while left < right ensures the prefix is reversed in place without redundant swaps or overruns.
for size in range(len(arr), 1, -1):
Iterate over prefix sizes from the full array length down to 2.
Processing from largest prefix to smallest ensures the largest unsorted element is placed correctly first, reducing the problem size stepwise.
if max_index == size - 1:
Skip flipping if the largest element is already at the end of the prefix.
Avoiding unnecessary flips when the largest element is in place optimizes the number of operations and prevents redundant work.
flip(max_index)
Record the flip size (max_index + 1) in the flips list.
Recording the flip size is necessary to output the sequence of operations that sorts the array.
flip(size - 1)
Record the flip size (current prefix size) in the flips list.
Appending this flip size documents the operation that completes the placement of the largest element.
def flip(end):
Define a helper function to reverse the prefix of the array up to a given index.
Encapsulating the prefix reversal logic in a function improves code clarity and reusability, isolating the core operation of pancake flipping.
max_index = 0
Initialize max_index to track the position of the largest element in the current prefix.
Tracking the largest element's index is necessary to determine where to flip to move it to the correct position.
continue
Continue to the next iteration if no flips are needed.
This control flow ensures the algorithm only performs flips when necessary, maintaining efficiency.
flips = []
Initialize an empty list to record the sizes of flips performed.
This list accumulates the sequence of prefix reversal sizes, which is the required output representing the pancake flips that sort the array.
left += 1
Increment left pointer to move towards the center.
Advancing the left pointer ensures the loop progresses and eventually terminates after reversing the prefix.
right -= 1
Decrement right pointer to move towards the center.
Moving the right pointer inward complements the left pointer's movement, enabling symmetric swaps and loop termination.
flips.append(size)
End of the for loop iteration, proceed to next smaller prefix.
Progressing to smaller prefixes ensures the algorithm sorts the array from largest to smallest elements.
left = 0
Initialize left pointer at the start of the prefix.
Starting the reversal from the beginning of the prefix is necessary to swap elements symmetrically towards the center.
right = end
Initialize right pointer at the end of the prefix.
The right pointer marks the boundary of the prefix to be reversed, enabling symmetric swaps with the left pointer.
Test Your Understanding
Why does flipping the largest unsorted element to the front before flipping the entire prefix guarantee progress towards sorting?
Because flipping the largest element to the front isolates it, allowing the subsequent flip of the entire prefix to move it directly to its correct position at the end of the unsorted prefix, effectively placing it in its final sorted position and reducing the problem size.
Related Problems
Greedy pattern
Don't just read it. Drill it.
Reconstruct Pancake Sorting from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Pancake Sorting drill