Magicsheet logo

Max Chunks To Make Sorted II

Hard
12.5%
Updated 8/1/2025

Max Chunks To Make Sorted II

What is this problem about?

This is the advanced version of "Max Chunks To Make Sorted". You are given an array of integers, but this time they are not a neat permutation of [0, n - 1]. The array can contain any integers, including duplicates. You must partition the array into the maximum number of chunks such that sorting each chunk individually and concatenating them results in a globally sorted array.

Why is this asked in interviews?

This Hard-level problem tests a candidate's ability to abstract sorting boundaries. The simple max_seen == index trick from Part I fails here because the values have no relation to the indices. Interviewers ask this to see if you can use Prefix Maximums and Suffix Minimums (or a Monotonic Stack) to logically deduce where cuts are mathematically safe.

Algorithmic pattern used

This problem leverages the Prefix Max and Suffix Min arrays (or a Monotonic Stack). For a cut to be valid between index i and i+1, every element in the left chunk must be less than or equal to every element in the right chunk. Therefore, if the maximum of all elements up to i (Prefix Max) is less than or equal to the minimum of all elements from i+1 to the end (Suffix Min), you can safely make a cut!

Example explanation

Array: [2, 1, 3, 4, 4]

  1. Calculate Suffix Mins (minimum from right to left): [1, 1, 3, 4, 4] (e.g., min from index 1 to end is 1).
  2. Iterate left to right tracking Prefix Max:
    • Index 0 (2): max_seen = 2. Check Suffix Min at index 1: 1. Is 212 \le 1? No.
    • Index 1 (1): max_seen = 2. Check Suffix Min at index 2: 3. Is 232 \le 3? Yes! Cut here! Chunks = 1.
    • Index 2 (3): max_seen = 3. Check Suffix Min at index 3: 4. Is 343 \le 4? Yes! Cut here! Chunks = 2.
    • Index 3 (4): max_seen = 4. Check Suffix Min at index 4: 4. Is 444 \le 4? Yes! Cut here! Chunks = 3.
    • Index 4 (4): End of array. Cut here! Chunks = 4. Total chunks = 4. ([2, 1], [3], [4], [4]).

Common mistakes candidates make

Candidates often attempt to sort the array and compare it with the original array element by element. While you can solve it by tracking the sum of the original array and sum of the sorted array (if sums match, cut), the Suffix Min/Prefix Max approach handles duplicates and large numbers much more robustly without needing the O(NlogN)O(N \log N) sorting time penalty.

Interview preparation tip

For the Max Chunks To Make Sorted II coding problem, mastering the Monotonic Stack approach is the ultimate flex. If you traverse the array and maintain a stack of the maximums of each chunk, when you encounter a new element, if it's smaller than the top of the stack, it must be merged into previous chunks (popping the stack until it's valid). The size of the stack at the end is your max chunks!

Similar Questions