MediumNo. 0969

Pancake Sorting — LeetCode 969 Python Solution

Topics
Greedy, Array, Two Pointers, Sorting
Reading time
4 min

The 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: Choose an integer k where 1 <= k <= arr.length.

Example

Input
arr = [3,2,4,1]
Output
[4,2,4,3]
Explanation
We perform 4 pancake flips, with k values 4, 2, 4, and 3.

Python solution

PythonSolution
class Solution:
    def pancakeSort(self, arr: List[int]) -> List[int]:
        def reverse(arr, j):
            i = 0
            while i < j:
                arr[i], arr[j] = arr[j], arr[i]
                i, j = i + 1, j - 1

        n = len(arr)
        ans = []
        for i in range(n - 1, 0, -1):
            j = i
            while j > 0 and arr[j] != i + 1:
                j -= 1
            if j < i:
                if j > 0:
                    ans.append(j + 1)
                    reverse(arr, j)
                ans.append(i + 1)
                reverse(arr, i)
        return ans

Complexity

Time
O(n) (after optional sort O(n log n))
Space · auxiliary
O(1)

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 969. Pancake Sorting is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0455Assign CookiesEasy
0611Valid Triangle NumberMedium
0826Most Profit Assigning WorkMedium
0870Advantage ShuffleMedium
0881Boats to Save PeopleMedium
0948Bag of TokensMedium

Frequently asked questions

How hard is LeetCode 969. Pancake Sorting?

LeetCode 969. Pancake Sorting is rated Medium on LeetCode.

What is the time complexity of LeetCode 969. Pancake Sorting?

The Python solution on this page runs in O(n) (after optional sort O(n log n)).

What is the space complexity of LeetCode 969. Pancake Sorting?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 969. Pancake Sorting cover?

LeetCode 969. Pancake Sorting is tagged Greedy, Array, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.