Pancake Sorting solution explained
Pancake Sorting is solved by placing the largest unsorted value one step at a time: flip the prefix that ends at it so it comes to the front, then flip the whole unsorted prefix so it drops into its final slot. Each value costs at most two flips, so the sequence has at most 2n - 3 flips and the work is O(n²) because every flip reverses up to n elements.
By Evin JohnPublished 8 min read
The problem in plain words
Picture a stack of pancakes of different sizes, with the top of the stack at index 0. The only move allowed is to slide a spatula under the top k pancakes and turn that group over, which reverses the first k entries of the list. Given a list containing each number from 1 to n exactly once, return a list of k values such that performing those flips in order leaves the list sorted ascending. Common versions allow up to ten flips per element, which is far more than the standard method needs.
| Start | Flips returned | What the flips do |
|---|---|---|
| [2, 4, 1, 3] | [2, 4, 3, 2] | 4 to front, 4 to back, 3 to back, then 2 into place |
| [3, 1, 2] | [3, 2] | 3 is already on top, so one flip sends it down; then [2, 1] needs one more |
| [1, 2, 3] | [] | Already sorted, nothing to do |
| [2, 1] | [2] | One full flip |
Clarify two things up front. First, are the values always exactly 1 to n? If they are arbitrary distinct numbers you compare against a sorted copy instead of using the value as its own target position. Second, is the shortest sequence required? Finding the minimum number of flips is a much harder problem, and almost every interview version only asks for some valid sequence.
Why it is a good interview problem
It looks like a puzzle, but it is really selection sort in disguise, with the restriction that the only primitive is a reversal of a prefix. Interviewers use it to see whether you can reduce an unfamiliar operation to an invariant you already know: after each round, the largest values sit at the end in their final positions. It also tests careful indexing, because the returned values are prefix lengths, not zero-based positions.
Slow approach: breadth-first search over orderings
Treat each arrangement of the list as a node, and each possible flip of size 2 to n as an edge. A breadth-first search from the starting order reaches the sorted order along a shortest path, which gives the minimum flip count. The catch is the size of the graph: n! arrangements, each with n - 1 neighbors, and building each neighbor copies the list. It is only usable for very small n, which makes it a good tool for checking your fast answer.
from collections import deque
def pancake_shortest(arr):
start, target = tuple(arr), tuple(sorted(arr))
came_from = {start: None}
queue = deque([start])
while queue:
state = queue.popleft()
if state == target:
break
for k in range(2, len(state) + 1):
nxt = state[:k][::-1] + state[k:]
if nxt not in came_from:
came_from[nxt] = (state, k)
queue.append(nxt)
flips, node = [], target
while came_from[node] is not None:
node, k = came_from[node]
flips.append(k)
return flips[::-1]Main approach: largest value to the front, then to its place
Work with a shrinking window. At the start, the window is the whole list and the largest value, n, belongs at the last index. Find where n sits. If it is already at the end, shrink the window and move on. Otherwise, flip the prefix ending at n so n comes to the top, then flip the whole window so n falls to the bottom of the window. Now n is final. Repeat with the window one shorter, looking for n - 1, and so on down to a window of two.
Two small savings keep the count down. If the target value is already at the top, skip the first flip, since a flip of size 1 changes nothing. If it is already at the bottom of the window, skip both. With those checks the sequence never exceeds 2n - 3 flips for n of at least 2, well inside the usual budget.
def pancake_sort(arr):
a = list(arr)
flips = []
for size in range(len(a), 1, -1):
pos = a.index(size)
if pos == size - 1:
continue
if pos > 0:
a[:pos + 1] = a[pos::-1]
flips.append(pos + 1)
a[:size] = a[size - 1::-1]
flips.append(size)
return flipsfunction pancakeSort(arr) {
const a = [...arr];
const flips = [];
const flip = (k) => {
for (let i = 0, j = k - 1; i < j; i++, j--) [a[i], a[j]] = [a[j], a[i]];
flips.push(k);
};
for (let size = a.length; size > 1; size--) {
const pos = a.indexOf(size);
if (pos === size - 1) continue;
if (pos > 0) flip(pos + 1);
flip(size);
}
return flips;
}In the Python slice a[pos::-1], the start is pos and the step is negative, so it yields a[pos], a[pos - 1], down to a[0]. That is exactly the reversed prefix of length pos + 1. Getting the stop value wrong here is the most common bug, so trace it once on a three-element list before moving on.
Trace on [2, 4, 1, 3]
- Window of 4, looking for 44 sits at index 1. Flip 2 gives [4, 2, 1, 3]. Flip 4 gives [3, 1, 2, 4].
- Window of 3, looking for 33 is already on top, so skip the first flip. Flip 3 gives [2, 1, 3, 4].
- Window of 2, looking for 22 is on top of a window of two. Flip 2 gives [1, 2, 3, 4]. Done with flips [2, 4, 3, 2].
Complexity
| Approach | Time | Extra space | Flips produced |
|---|---|---|---|
| Breadth-first search | O(n! × n²) | O(n! × n) | The minimum possible |
| Largest to front, then down | O(n²) | O(n) | At most 2n - 3 |
The O(n²) comes from n rounds, each with a linear search for the target and up to two reversals of linear length. You cannot easily beat that with this primitive, since each reversal is itself linear work on an array.
Edge cases to test
- A list that is already sorted: return an empty list of flips.
- A list sorted in reverse: a single full flip fixes it, and the method finds that on the first round.
- A single element: no flips.
- The maximum already at the top: the first flip of the round must be skipped or harmlessly written as size 1.
- Arbitrary distinct values instead of 1 to n: compare against a sorted copy to know which value to look for.
Mistakes that cost points
- Returning zero-based indexes instead of prefix lengths. A flip that moves index 2 to the top has length 3.
- Searching the whole list for the target instead of only the unsorted window. Because the target value is unique this still works, but say why.
- Forgetting to actually apply the flips to the working copy, so later searches look at stale positions.
- Mutating the caller's list when the problem asks only for the flip sequence. Copy first unless told otherwise.
- Promising the minimum number of flips. This method is valid, not optimal.
How to explain it out loud
Fictional example
- Candidate
- A flip can only move something to the top or push the top down, so I will place the biggest unplaced value each round, like selection sort.
- Candidate
- If the biggest one is in the middle, one flip brings it to the top and a second flip of the whole unsorted part sends it to the end. Then I shrink the window by one.
- Candidate
- That is at most two flips per value, so fewer than 2n flips overall, and O(n squared) work since each flip reverses up to n items. It is not the shortest sequence, which the problem does not ask for.
Related problems in this set
Wiggle Sort II is another arrangement task where the goal is a pattern rather than full order. H-Index II switches to sorted input and asks for a fast search instead of a rearrangement. For the selection idea and other sorting families, the algorithm interview questions page is a good reference, and the software engineer interview questions page shows where problems like this fit in a full loop.
Rehearse it with Natively
This is a problem where saying the invariant clearly matters as much as the code. During practice, Natively can read the prompt from a screenshot and offer an approach, and it can transcribe your mock answer on the computer so you can check afterwards whether you explained why each value needs at most two flips. Read about an AI interview assistant for Mac and Windows.
Questions people ask
How does the pancake sorting algorithm work?
For each window size from n down to 2, find the largest unplaced value, flip the prefix ending at it so it comes to the top, then flip the whole window so it lands at the bottom. Each value needs at most two flips.
What is the time complexity of pancake sorting?
O(n²) time, because there are n rounds and each one does a linear search plus up to two linear reversals. The method produces at most 2n - 3 flips.
Does pancake sorting return the minimum number of flips?
No. The standard method returns a valid sequence, not the shortest one. Finding the minimum is much harder, and a breadth-first search over arrangements only works for very small inputs.
Are the returned values indexes or lengths?
Lengths. Each value k means reverse the first k elements, so a flip that brings index 2 to the top is written as 3.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
