Max Chunks To Make Sorted (LeetCode 769): Solution and Explanation
Split a permutation of 0..n-1 into the most chunks so that sorting each chunk sorts the whole array.
Intuition
A chunk boundary after index i is allowed only when nothing to the left has to move right of i once sorted. In other words, every value seen so far must be smaller than every value still to come.
Think of each chunk by its largest value. When a new value x is bigger than every chunk max so far, it can safely start its own chunk.
When x is smaller than some chunk maxima, x must end up left of those values after sorting, so those chunks and x have to become one chunk. The merged chunk keeps the biggest max.
Storing chunk maxima on a stack keeps them increasing from bottom to top, so the chunks that need merging are always the ones on top.
Approach: Monotonic stack of chunk maxima
- Start with an empty stack.
- For each value
x: if the stack is empty orx > stack[-1], pushxas a new chunk. - Otherwise pop the top as
head(the largest max so far), then pop every remaining top greater thanx, since those chunks must merge withx. - Push
headback. It now represents the single merged chunk. - Return the stack size.
Step-by-step example
arr = [0,2,1,4,5,3,6]
- 0: stack empty, push. stack = [0].
- 2 > 0: push. stack = [0, 2]. 1 < 2: pop head 2, 0 is not greater than 1, push 2 back. stack = [0, 2], chunk [1..2].
- 4 > 2: push. 5 > 4: push. stack = [0, 2, 4, 5].
- 3 < 5: pop head 5, then 4 > 3 is popped too, 2 stays. Push 5. stack = [0, 2, 5], chunk [3..5].
- 6 > 5: push. stack = [0, 2, 5, 6], so the answer is 4: [0] [2,1] [4,5,3] [6].
Code: Python, Java, C++
1class Solution:
2 def maxChunksToSorted(self, arr: List[int]) -> int:
3 stack = []
4 for x in arr:
5 if not stack or x > stack[-1]:
6 stack.append(x)
7 else:
8 head = stack.pop()
9 while stack and stack[-1] > x:
10 stack.pop()
11 stack.append(head)
12 return len(stack)1class Solution {
2 public int maxChunksToSorted(int[] arr) {
3 Deque<Integer> stack = new ArrayDeque<>();
4 for (int x : arr) {
5 if (stack.isEmpty() || x > stack.peek()) {
6 stack.push(x);
7 } else {
8 int head = stack.pop();
9 while (!stack.isEmpty() && stack.peek() > x) {
10 stack.pop();
11 }
12 stack.push(head);
13 }
14 }
15 return stack.size();
16 }
17}1class Solution {
2public:
3 int maxChunksToSorted(vector<int>& arr) {
4 vector<int> stack;
5 for (int x : arr) {
6 if (stack.empty() || x > stack.back()) {
7 stack.push_back(x);
8 } else {
9 int head = stack.back();
10 stack.pop_back();
11 while (!stack.empty() && stack.back() > x) {
12 stack.pop_back();
13 }
14 stack.push_back(head);
15 }
16 }
17 return stack.size();
18 }
19};Time and space complexity
O(n)
Each value is pushed once and popped at most once.
O(n)
The stack can hold one entry per element when the array is already sorted.
Other approaches
Running maximum equals index (time O(n), space O(1))
Because arr is a permutation of 0..n-1, a chunk can end at i exactly when max(arr[0..i]) == i. Count those indices.
Prefix max vs suffix min (time O(n), space O(n))
Cut after i when the prefix max is smaller than the suffix min starting at i + 1. This also works when values repeat (Max Chunks To Make Sorted II).
Common mistakes
- Popping only one chunk when a small value arrives. The value may need to travel past several chunks, so keep popping while the top max is larger than it.
- Forgetting to push the head back after merging. The merged chunk still exists and its max is the old head.
- Counting positions where arr[i] == i. A value can be in place while a bigger value to its left still has to move past it.
Frequently asked questions
Why does the stack stay increasing?
A value is pushed only when it beats the top, and after a merge the head that is pushed back is larger than every value left below it. So maxima grow from bottom to top.
Why use a stack when max(arr[0..i]) == i is simpler?
The index trick depends on arr being a permutation of 0..n-1. The stack works for any values, including duplicates, which is the follow-up problem.