Skip to content

Commit 98e4a70

Browse files
authored
Merge pull request #4011 from ImmidiSivani/leetcode-969
solution added to 969
2 parents 1bb016f + 9778376 commit 98e4a70

File tree

1 file changed

+178
-0
lines changed

1 file changed

+178
-0
lines changed
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
---
2+
id: pancake-sorting
3+
title: Pancake Sorting
4+
sidebar_label: 969-Pancake Sorting
5+
tags:
6+
- Sorting
7+
- Array
8+
- LeetCode
9+
- Java
10+
- Python
11+
- C++
12+
description: "This is a solution to the Pancake Sorting problem on LeetCode."
13+
sidebar_position: 13
14+
---
15+
16+
## Problem Description
17+
18+
Given an array of integers `arr`, sort the array by performing a series of pancake flips.
19+
20+
In one pancake flip, we do the following steps:
21+
1. Choose an integer `k` where `1 <= k <= arr.length`.
22+
2. Reverse the sub-array `arr[0...k-1]` (0-indexed).
23+
24+
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`.
25+
26+
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.
27+
28+
### Examples
29+
30+
**Example 1:**
31+
32+
```
33+
Input: arr = [3,2,4,1]
34+
Output: [4,2,4,3]
35+
Explanation:
36+
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
37+
Starting state: arr = [3, 2, 4, 1]
38+
After 1st flip (k = 4): arr = [1, 4, 2, 3]
39+
After 2nd flip (k = 2): arr = [4, 1, 2, 3]
40+
After 3rd flip (k = 4): arr = [3, 2, 1, 4]
41+
After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.
42+
```
43+
44+
**Example 2:**
45+
46+
```
47+
Input: arr = [1,2,3]
48+
Output: []
49+
Explanation: The input is already sorted, so there is no need to flip anything.
50+
Note that other answers, such as [3, 3], would also be accepted.
51+
```
52+
53+
### Constraints
54+
55+
- `1 <= arr.length <= 100`
56+
- `1 <= arr[i] <= arr.length`
57+
- All integers in `arr` are unique (i.e., `arr` is a permutation of the integers from 1 to `arr.length`).
58+
59+
---
60+
61+
## Solution for Pancake Sorting Problem
62+
63+
To solve this problem, we perform a series of pancake flips to sort the array in ascending order. A pancake flip reverses the sub-array from the start to a chosen index `k`. The goal is to bring the largest unsorted element to its correct position iteratively.
64+
65+
### Approach
66+
67+
1. **Identify Largest Element:** Find the largest unsorted element in the array.
68+
2. **Bring to Front:** If this largest element is not already at the front, flip it to bring it to the front.
69+
3. **Move to Correct Position:** Flip the entire sub-array up to the correct position of the largest element to place it at its sorted position.
70+
4. **Repeat:** Repeat the above steps for the next largest unsorted elements, excluding the already sorted part of the array.
71+
72+
### Code in Different Languages
73+
74+
<Tabs>
75+
<TabItem value="C++" label="C++" default>
76+
<SolutionAuthor name="@ImmidiSivani"/>
77+
78+
```cpp
79+
class Solution {
80+
public:
81+
vector<int> pancakeSort(vector<int>& arr) {
82+
vector<int> res;
83+
int n = arr.size();
84+
for (int i = n; i > 1; --i) {
85+
int maxIdx = max_element(arr.begin(), arr.begin() + i) - arr.begin();
86+
if (maxIdx == i - 1) continue;
87+
if (maxIdx != 0) {
88+
res.push_back(maxIdx + 1);
89+
reverse(arr.begin(), arr.begin() + maxIdx + 1);
90+
}
91+
res.push_back(i);
92+
reverse(arr.begin(), arr.begin() + i);
93+
}
94+
return res;
95+
}
96+
};
97+
```
98+
99+
</TabItem>
100+
<TabItem value="Java" label="Java">
101+
<SolutionAuthor name="@ImmidiSivani"/>
102+
103+
```java
104+
class Solution {
105+
public List<Integer> pancakeSort(int[] arr) {
106+
List<Integer> res = new ArrayList<>();
107+
int n = arr.length;
108+
for (int i = n; i > 1; --i) {
109+
int maxIdx = findMaxIndex(arr, i);
110+
if (maxIdx == i - 1) continue;
111+
if (maxIdx != 0) {
112+
res.add(maxIdx + 1);
113+
flip(arr, maxIdx + 1);
114+
}
115+
res.add(i);
116+
flip(arr, i);
117+
}
118+
return res;
119+
}
120+
121+
private int findMaxIndex(int[] arr, int k) {
122+
int maxIdx = 0;
123+
for (int i = 1; i < k; i++) {
124+
if (arr[i] > arr[maxIdx]) {
125+
maxIdx = i;
126+
}
127+
}
128+
return maxIdx;
129+
}
130+
131+
private void flip(int[] arr, int k) {
132+
for (int i = 0, j = k - 1; i < j; i++, j--) {
133+
int temp = arr[i];
134+
arr[i] = arr[j];
135+
arr[j] = temp;
136+
}
137+
}
138+
}
139+
```
140+
141+
</TabItem>
142+
<TabItem value="Python" label="Python">
143+
<SolutionAuthor name="@ImmidiSivani"/>
144+
145+
```python
146+
class Solution:
147+
def pancakeSort(self, arr: List[int]) -> List[int]:
148+
res = []
149+
n = len(arr)
150+
for i in range(n, 1, -1):
151+
max_idx = arr.index(max(arr[:i]))
152+
if max_idx == i - 1:
153+
continue
154+
if max_idx != 0:
155+
res.append(max_idx + 1)
156+
arr[:max_idx + 1] = arr[:max_idx + 1][::-1]
157+
res.append(i)
158+
arr[:i] = arr[:i][::-1]
159+
return res
160+
```
161+
162+
</TabItem>
163+
</Tabs>
164+
165+
#### Complexity Analysis
166+
167+
- **Time Complexity**: $O(n^2)$, where `n` is the length of the array. Finding the maximum and flipping can each take up to `O(n)`, and we do this for each of the `n` elements.
168+
- **Space Complexity**: $O(1)$, excluding the output list.
169+
170+
---
171+
172+
<h2>Authors:</h2>
173+
174+
<div style={{display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: '10px'}}>
175+
{['ImmidiSivani'].map(username => (
176+
<Author key={username} username={username} />
177+
))}
178+
</div>

0 commit comments

Comments
 (0)