Max Chunks To Make Sorted solution explained

Max Chunks To Make Sorted has a one-line test: when the array holds each of 0 to n - 1 once, you can end a chunk after index i exactly when the largest value seen so far equals i, because then positions 0 to i hold precisely the values 0 to i. Count those indexes in one pass, O(n) time and O(1) space. For arrays with repeated values, a monotonic stack of chunk maxima does the same job.

By Published 7 min read

The problem in plain words

You get an array that contains every whole number from 0 to n - 1 exactly once, in some order. Cut it into contiguous pieces. Sort each piece on its own, then put the pieces back in their original order. If the result is the sorted array 0, 1, ..., n - 1, the cut is acceptable. Return the largest number of pieces an acceptable cut can have.

Arrays made up for this page; answers from the code below
ArrayRunning maximumChunksPieces
[2, 0, 1, 3, 5, 4]2, 2, 2, 3, 5, 53[2, 0, 1] [3] [5, 4]
[1, 0, 3, 2, 4]1, 1, 3, 3, 43[1, 0] [3, 2] [4]
[0, 1, 2, 3]0, 1, 2, 34Every element alone
[4, 0, 1, 2, 3]4, 4, 4, 4, 41The 4 at the front forces one piece
[3, 2, 1, 0]3, 3, 3, 31Fully reversed
Arrays made up for this page; answers from the code below. Scroll sideways on a small screen.

What the interviewer checks

This problem rewards finding the right invariant before writing code. The interviewer wants to hear a precise condition for a valid cut and a reason why taking every valid cut is optimal. The second half of the conversation is often the version with repeated values, which needs a stack, so it is worth knowing both.

Brute force: every set of cuts

from itertools import combinations

def most_chunks_slow(arr):
    # try every set of cut points; keep the largest set that still sorts correctly
    n = len(arr)
    target = sorted(arr)
    for cuts in range(n - 1, -1, -1):
        for points in combinations(range(1, n), cuts):
            bounds = [0, *points, n]
            joined = []
            for a, b in zip(bounds, bounds[1:]):
                joined += sorted(arr[a:b])
            if joined == target:
                return cuts + 1
    return 1
Try cut sets from most cuts to fewest; return the first that works. Exponential.

Useful only as a test oracle. It does hint at the structure, though: whether a cut set works depends on each cut separately, which suggests checking cuts one at a time.

The running-maximum test

Consider cutting right after index i. Sorting the pieces cannot move a value across the cut. So the cut is acceptable only if positions 0 to i already hold the values that belong there, which are 0 to i. Those are i + 1 distinct values from the range 0..n-1; they are exactly {0, ..., i} if and only if the largest of them is i. So the cut after i is valid exactly when the running maximum equals i.

Why take every valid cut? Each valid cut is valid on its own merits, regardless of the others: the left side holds the right values whatever happens elsewhere. Pieces between two valid cuts then hold exactly the values that belong between them, so sorting each piece works. The number of chunks is the number of valid cuts (the end of the array always counts as one).

def most_chunks(arr):
    chunks = 0
    highest = -1
    for i, value in enumerate(arr):
        highest = max(highest, value)
        if highest == i:       # positions 0..i hold exactly the values 0..i
            chunks += 1
    return chunks
Python: count indexes where the running maximum equals the index. O(n) time, O(1) space.
function mostChunks(arr) {
  let chunks = 0, highest = -1;
  arr.forEach((value, i) => {
    highest = Math.max(highest, value);
    if (highest === i) chunks++;
  });
  return chunks;
}
JavaScript version.

Trace on the first example

[2, 0, 1, 3, 5, 4]: at index 0 the maximum is 2, not 0, so no cut. Index 1, max 2. Index 2, max 2 equals 2: cut, chunk one is [2, 0, 1]. Index 3, max 3 equals 3: cut, chunk two is [3]. Index 4, max 5. Index 5, max 5 equals 5: chunk three is [5, 4]. Answer 3.

When values can repeat

A common follow-up drops the permutation rule: any integers, repeats allowed. The running-maximum test no longer works because values do not tell you their own positions. Instead, keep a stack where each entry is the largest value of one chunk built so far, with entries non-decreasing from bottom to top. A new value at least as big as the top starts a new chunk. A smaller value must join every chunk whose maximum exceeds it, so pop those chunks, then push back the biggest of the merged maxima. The stack's final size is the answer, still O(n).

def most_chunks_any_values(arr):
    # each stack entry is the largest value of one chunk; tops stay non-decreasing
    stack = []
    for value in arr:
        if stack and value < stack[-1]:
            biggest = stack.pop()
            while stack and value < stack[-1]:
                stack.pop()            # merge chunks that this value must join
            stack.append(biggest)
        else:
            stack.append(value)
    return len(stack)
Monotonic stack of chunk maxima, for arrays with any values.

On [3, 1, 2, 2, 5, 4, 6] this gives 3: [3, 1, 2, 2], [5, 4] and [6]. The 1 merges into the chunk headed by 3, the two 2s stay inside it, the 4 merges into the chunk headed by 5, and the 6 starts its own.

Complexity

n elements
ApproachTimeExtra space
Every cut setO(2^n · n log n)O(n)
Running maximum (permutation)O(n)O(1)
Stack of chunk maxima (any values)O(n)O(n)
Prefix max vs suffix min (any values)O(n)O(n)
n elements. Scroll sideways on a small screen.

The last row is another route for the repeated-values version: a cut after i is valid when the largest value on the left is at most the smallest value on the right. Precompute suffix minimums and count.

Edge cases

  • One element: one chunk.
  • Already sorted: n chunks, every index is a valid cut.
  • The largest value at index 0: only one chunk is possible.
  • Reversed: one chunk.

Mistakes to watch for

  • Comparing each value with its own index (arr[i] == i) instead of the running maximum. That gives 1 for [0, 2, 1] (the right answer is 2) and 0 for [1, 0] (the right answer is 1).
  • Using the permutation shortcut on an array with repeats or values outside 0..n-1.
  • In the stack version, pushing the new small value instead of the merged chunk's maximum.
  • Counting cuts instead of chunks and ending up one short.

How to explain it out loud

Fictional example

Stating the invariant clearly
Candidate
Sorting a chunk can't move values across a cut, so a cut after index i needs the left side to hold exactly 0 through i.
Candidate
Since the values are a permutation, that's true exactly when the maximum so far equals i. Each valid cut stands on its own, so I take all of them.
Candidate
One pass, constant space. If values can repeat, I'd switch to a stack of chunk maxima and merge chunks when a smaller value arrives.

The repeated-values version uses the same kind of stack as Next Greater Element II and 132 Pattern. Partition Labels asks a close cousin: cut a string into the most pieces where each letter stays in one piece, solved with a running farthest-reach. See also the coding problems hub.

Natively during practice

When you practice on a Mac or Windows machine, Natively can pick up this problem from a screenshot and test your invariant with you, or walk through the stack merge on an array with repeats. Its notes and transcript from the mock are kept on your computer for review. Details on the AI interview assistant page.

Questions people ask

How do you solve Max Chunks To Make Sorted?

Walk the array keeping the largest value seen so far. Each index where that maximum equals the index is a valid cut, because the left side then holds exactly 0 to i. The answer is how many such indexes there are.

Why does the running maximum work for Max Chunks To Make Sorted?

The values are a permutation of 0..n-1, so i + 1 distinct values from that range are exactly {0..i} only when their maximum is i. Each valid cut stands on its own, so taking all of them is optimal.

How do you solve Max Chunks To Make Sorted II with repeated values?

Keep a stack of chunk maxima. A value at least as big as the top starts a new chunk; a smaller value pops and merges every chunk with a bigger maximum, then the merged maximum is pushed back. The stack size is the answer.

What is the time complexity of Max Chunks To Make Sorted?

O(n) time and O(1) space for the permutation version, and O(n) time and space for the stack version with repeats.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP