The Max Chunks To Make Sorted problem gives you an array arr of length n that represents a permutation of the integers in the range [0, n - 1]. You must split the array into some number of contiguous "chunks" (partitions). The rule is: if you sort each individual chunk in ascending order and then concatenate them back together, the entire array must end up perfectly sorted. Your goal is to return the maximum number of chunks you can create.
This problem is a brilliant test of logical deduction and array properties. Interviewers ask it because candidates who try to simulate the sorting process will create overly complex solutions. Candidates who understand the properties of a permutation can solve it in a highly elegant pass. It evaluates your ability to track maximums and recognize alignment states.
This problem uses a Greedy / Running Maximum pattern. Because the array is a permutation of [0, n - 1], the perfectly sorted array will simply have the value i at index i.
Therefore, as we iterate through the array, we keep track of the maximum value seen so far. If the running maximum is exactly equal to the current index, it means all the numbers required to fill the positions up to index have been encountered! We can safely make a cut (create a chunk) right at this index.
Array: [1, 0, 2, 3, 4]
max_seen = 1. max_seen != index (1 != 0). No chunk.max_seen = 1. max_seen == index (1 == 1). All numbers from 0 to 1 are in this block. Cut! Chunk count = 1.max_seen = 2. max_seen == index (2 == 2). Cut! Chunk count = 2.max_seen = 3. max_seen == index (3 == 3). Cut! Chunk count = 3.max_seen = 4. max_seen == index (4 == 4). Cut! Chunk count = 4.
Total maximum chunks = 4. (Chunks are [1, 0], [2], [3], [4]).A common mistake is trying to track the minimum value as well, or attempting to use a Monotonic Stack, which overcomplicates the logic. Because the values are strictly 0 to n - 1, the running maximum is the only variable you need to track. If the max value matches the index, the math guarantees that all smaller required values are trapped behind it.
When tackling the Max Chunks To Make Sorted interview question, pay very close attention to the constraint: "permutation of integers [0, n - 1]". Whenever an array's values directly correspond to its valid indices, you have a massive mathematical advantage. Track the max and check if it aligns with the index—it's one of the cleanest tricks in array problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| The Number of Weak Characters in the Game | Medium | Solve | |
| Max Chunks To Make Sorted II | Hard | Solve | |
| Shortest Unsorted Continuous Subarray | Medium | Solve | |
| Car Fleet | Medium | Solve | |
| Make Array Non-decreasing | Medium | Solve |