#969
Pancake Sorting
MediumArrayTwo PointersGreedySortingGreedyTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution involves iteratively placing the largest unsorted element in its correct position using a two-step flip process, minimizing the number of flips required.
⚙️
Algorithm
3 steps- 1Step 1: Iterate through the array from the last element to the first.
- 2Step 2: For each element, find the index of the maximum element in the unsorted portion.
- 3Step 3: If the maximum element is not in its correct position, perform a flip to bring it to the front, then flip it to its correct position.
solution.py15 lines
1def pancakeSort(arr):
2 def flip(k):
3 arr[:k] = arr[:k][::-1]
4
5 res = []
6 n = len(arr)
7 for i in range(n, 1, -1):
8 max_index = arr.index(max(arr[:i]))
9 if max_index != i - 1:
10 if max_index != 0:
11 flip(max_index + 1)
12 res.append(max_index + 1)
13 flip(i)
14 res.append(i)
15 return resℹ
Complexity note: The optimal solution runs in O(n) time because we only need to find the maximum element and flip it to its correct position in a single pass, and we use additional space for the result.
- 1Pancake sorting is a greedy algorithm that focuses on placing the largest unsorted element in its correct position.
- 2The two-step flip process minimizes the number of flips needed to sort the array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.