Max Chunks To Make Sorted

Split an array of the numbers 0 to n - 1 into as many pieces as possible, so that sorting each piece sorts the whole array.

You are given an array arr of length n that holds each of the numbers 0 to n - 1 exactly once, in some order. Split it into chunks, where a chunk is a run of neighbouring positions, and sort each chunk on its own. Then join the chunks back in their original order. Return the largest number of chunks for which the joined array is fully sorted.

Example 1
Input: arr = [4, 3, 2, 1, 0]
Output: 1
Explanation: the 4 at the front belongs at the end, so the only chunk that works is the whole array.
Example 2
Input: arr = [1, 0, 2, 3, 4]
Output: 4
Explanation: the chunks [1, 0], [2], [3] and [4] sort into [0, 1], [2], [3] and [4].
Solution

The Idea

Picture five numbered cards in a row: 1, 0, 2, 3, 4. You may split the row into groups of neighbouring cards, sort each group on its own, and leave the groups in their places. You want the row to end up as 0, 1, 2, 3, 4, with as many groups as possible. Splitting it into [1, 0], [2], [3] and [4] works: sorting [1, 0] gives [0, 1], and the other groups are already in order. So the answer is 4.

Example 1 is the opposite case. In [4, 3, 2, 1, 0] the 4 sits at the front, but it belongs at the end. Sorting a group never moves a card into another group, so the 4 can only reach the end if its group runs to the end. The whole row has to be one group, and the answer is 1.

So where may we cut? A cut after a position is fine only when every card to its left belongs on the left. In Example 2, counting positions from 0, after position 1 the left side holds 1 and 0. Those are exactly the cards that the sorted row puts at positions 0 and 1. After position 0, the left side holds only the 1, which belongs at position 1, on the other side of the cut.

How can we tell quickly that positions 0 to i hold exactly the numbers 0 to i? Look at the largest of them. Positions 0 to i hold i + 1 different numbers. If the largest is i, they can only be 0, 1, ..., i, because those are the only i + 1 numbers that are not bigger than i. Look at the picture below.

The array 1, 0, 2, 3, 4 with the largest value so far under each position: 1, 1, 2, 3, 4. At position 0 the largest so far is 1, so there is no cut. At positions 1, 2 and 3 it equals the position, so a cut follows each, giving the chunks [1, 0], [2], [3] and [4].

Under each card is the largest value so far. At position 0 it is 1, bigger than the position, so there is no cut there. At position 1 it is still 1, equal to the position, so a cut follows. After that each card is the new largest value and equals its position, so each one ends with a cut of its own. The last card needs no cut, because the array ends there.

So the whole problem comes down to one number carried from left to right: the largest value seen so far. Keeping that number while walking along an array is called a running maximum. Every position where it equals the position ends a chunk.

Solution Approach

Turning that idea into code means settling three things: which places allow a cut, how to test a place in one step, and why cutting at every allowed place gives the most chunks.

Places that allow a cut

Why not simply try every way of cutting? An array of n numbers has n - 1 gaps between neighbours, and each gap is either cut or not, which gives 2n - 1 ways. For 30 numbers that is more than 500 million splits, each to be sorted and checked.

Each gap can be judged on its own instead. Sorting a chunk only rearranges the numbers inside it, and the sorted array puts the number v at position v. So a cut after position i is allowed exactly when positions 0 to i already hold the numbers 0 to i, in any order.

Testing a place in one step

How do we check "positions 0 to i hold 0 to i" without sorting them each time? With the running maximum from the picture. The variable max keeps the largest value seen so far, and each new position updates it with Math.max. When max equals i, the i + 1 different numbers on the left are all at most i, so they are exactly 0 to i.

The last position always passes this test, because the largest number in the whole array is n - 1. That match counts the final chunk, so counting the matches counts the chunks.

Using every allowed place

Is it safe to cut at all the allowed places at once? Take two neighbouring cuts, after position i and after position j. The left side of the second cut holds 0 to j, and the left side of the first holds 0 to i. So the chunk between them holds exactly i + 1 to j, and sorting it puts each number in its place.

A cut anywhere else leaves some number on the wrong side, which no sorting can fix. So a valid split can only use allowed places, and using all of them gives the most chunks.

Java Solution

The method maxChunksToSorted works in these steps:

  1. First, set chunks, the number of chunks found so far, to 0, and max, the largest value seen so far, to 0.
  2. Walk along the array with one loop, moving i from the first position to the last. At each position, update max with Math.max(max, arr[i]), so it holds the largest value in positions 0 to i.
  3. If max equals i, positions 0 to i hold exactly the numbers 0 to i, so a chunk ends here: add 1 to chunks.
  4. When the loop is done, return chunks.

The main method runs both examples, a single number, an array that is already sorted, and [2, 0, 1, 4, 3], where both chunks hold more than one number.

Java
import java.util.Arrays;

public class MaxChunksToMakeSorted {

    public static int maxChunksToSorted(int[] arr) {
        int chunks = 0;
        int max = 0;
        for (int i = 0; i < arr.length; i++) {
            max = Math.max(max, arr[i]);    // largest value in arr[0..i]
            if (max == i) {                 // arr[0..i] holds exactly 0..i
                chunks++;
            }
        }
        return chunks;
    }

    public static void main(String[] args) {
        int[][] inputs = {
            {4, 3, 2, 1, 0},
            {1, 0, 2, 3, 4},
            {0},
            {0, 1, 2, 3},
            {2, 0, 1, 4, 3}
        };
        for (int[] arr : inputs) {
            String shown = Arrays.toString(arr);
            System.out.println(shown + " -> " + maxChunksToSorted(arr));
        }
    }
}

Running it prints:

Output
[4, 3, 2, 1, 0] -> 1
[1, 0, 2, 3, 4] -> 4
[0] -> 1
[0, 1, 2, 3] -> 4
[2, 0, 1, 4, 3] -> 2

On [4, 3, 2, 1, 0], max becomes 4 at the first position and only equals i at the last one, so the count is 1. The 4 on the next line matches the cuts in the picture. A single number is one chunk, and the sorted [0, 1, 2, 3] gives 4, one chunk per number.

Look at the last line, 2. max reaches 2 at position 2, which closes the chunk [2, 0, 1], and 4 at position 4, which closes [4, 3]. In between, at positions 0, 1 and 3, max is bigger than i, so no chunk ends there.

Comparing each number with its own position, arr[i] == i, looks like a shortcut but tests one number instead of everything on the left. Run on these arrays, it counts 3 for [1, 0, 2, 3, 4] and 0 for [2, 0, 1, 4, 3], because no number in [1, 0], [2, 0, 1] or [4, 3] sits in its own place.

Complexity

The work is a single pass over the array, keeping a count of chunks and the largest value so far.

  • Time: O(n), because the loop visits each of the n positions once and does one Math.max and one comparison there.
  • Space: O(1). Only chunks, max and i are kept, and the array is only read, never copied or sorted.

Partition Labels splits a string with a similar scan: it carries the farthest point the current part must reach, and cuts when the walk gets there.