← Home

969. Pancake Sorting

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
969

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 969. Pancake Sorting, the solution in this repository is mainly a greedy solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

The notes already sitting in the source point us in the right direction:

  • Approach 1: Sort Largest to Smallest

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are pancakeSort, indices.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N^2), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Approach 1: Sort Largest to Smallest
02//Runtime: 8 ms, faster than 69.75% of C++ online submissions for Pancake Sorting.
03//Memory Usage: 8.7 MB, less than 100.00% of C++ online submissions for Pancake Sorting.
04class Solution {
05public:
06    vector<int> pancakeSort(vector<int>& A) {
07        vector<int> ans;
08        
09        //skip curmax = 1 because 1 must be in correct place 
10        // when all other elements all in correct place
11        for(int curmax = A.size(); curmax >= 2; curmax--){
12            int index = find(A.begin(), A.end(), curmax) - A.begin();
13            //make index 1-based
14            index += 1;
15            // cout << curmax << ", " << index << endl;
16            
17            if(index > 1){
18                //"last" is exclusive, so A[0], ..., A[index-1]
19                reverse(A.begin(), A.begin() + index);
20                // copy(A.begin(), A.end(), ostream_iterator<int>(cout, " "));
21                // cout << endl;
22                ans.push_back(index);
23            }
24            
25            if(curmax > 1){
26                //A[0], ..., A[curmax-1]
27                reverse(A.begin(), A.begin() + curmax);
28                // copy(A.begin(), A.end(), ostream_iterator<int>(cout, " "));
29                // cout << endl;
30                ans.push_back(curmax);
31            }
32            
33        }
34        
35        return ans;
36    }
37};
38
39//without actually flipping
40//official solution
41//time: O(N^2), space: O(N)
42//Runtime: 8 ms, faster than 69.75% of C++ online submissions for Pancake Sorting.
43//Memory Usage: 8.8 MB, less than 83.33% of C++ online submissions for Pancake Sorting.
44class Solution {
45public:
46    vector<int> pancakeSort(vector<int>& A) {
47        vector<int> ans;
48        int N = A.size();
49        
50        vector<int> indices(N);
51        iota(indices.begin(), indices.end(), 1);
52        //the larget the former
53        sort(indices.begin(), indices.end(), 
54             [&A](const int i, const int j){return A[i-1] > A[j-1];});
55        // copy(indices.begin(), indices.end(), ostream_iterator<int>(cout, " "));
56        // cout << endl;
57        
58        for(int index : indices){
59            //don't actually reverse the vector, but simulate it
60            // cout << index << "->";
61            for(int flip : ans){
62                if(index <= flip){
63                    //flip at flip'th position, so index'th position is affected
64                    //old position + new position = flipped vector's size + 1
65                    index = flip + 1 - index;
66                }
67            }
68            // cout << index << endl;
69            //now index becomes the true index after serveral flipping
70            ans.push_back(index);
71            ans.push_back(N--);
72        }
73        
74        return ans;
75    }
76};

Cost

Complexity

Time
O(N^2), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.