LeetCode 969: Pancake Sorting Solution

Master LeetCode problem 969 (Pancake Sorting), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

969. Pancake Sorting

Problem Explanation

Explanation:

The problem requires us to sort an array using pancake flips. We can approach this problem by iteratively finding the largest element in the unsorted portion of the array and performing pancake flips to move it to the correct position in the sorted portion.

  1. For each iteration:

    • Find the index of the largest element in the unsorted portion.
    • Perform two pancake flips:
      • First, flip the subarray to move the largest element to the beginning.
      • Then, flip the entire subarray to move the largest element to its correct position.
  2. Repeat the above steps until the array is sorted.

The time complexity of this approach is O(n^2) and the space complexity is O(1), where n is the length of the input array. :

Solution Code

class Solution {
    public List<Integer> pancakeSort(int[] arr) {
        List<Integer> flips = new ArrayList<>();
        for (int end = arr.length; end > 0; end--) {
            int maxIndex = findMaxIndex(arr, end);
            if (maxIndex == end - 1) {
                continue;
            }
            if (maxIndex != 0) {
                flips.add(maxIndex + 1);
                flip(arr, maxIndex);
            }
            flips.add(end);
            flip(arr, end - 1);
        }
        return flips;
    }
    
    private int findMaxIndex(int[] arr, int end) {
        int maxIndex = 0;
        for (int i = 0; i < end; i++) {
            if (arr[i] > arr[maxIndex]) {
                maxIndex = i;
            }
        }
        return maxIndex;
    }
    
    private void flip(int[] arr, int k) {
        int i = 0, j = k;
        while (i < j) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;
            j--;
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 969 (Pancake Sorting)?

This page provides optimized solutions for LeetCode problem 969 (Pancake Sorting) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 969 (Pancake Sorting)?

The time complexity for LeetCode 969 (Pancake Sorting) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 969 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 969 in Java, C++, or Python.

Back to LeetCode Solutions