Max Chunks To Make Sorted - Problem
You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Input & Output
Example 1 — Maximum Chunks
$
Input:
arr = [4,3,2,1,0]
›
Output:
1
💡 Note:
The array is completely reverse sorted. We need the maximum element 4 to reach its correct position at index 4, so we can only make 1 chunk containing all elements.
Example 2 — Multiple Chunks
$
Input:
arr = [1,0,2,3,4]
›
Output:
4
💡 Note:
We can split into chunks: [1,0] (sorts to [0,1]), [2], [3], [4]. After concatenating: [0,1,2,3,4] which is the sorted array.
Example 3 — Already Sorted
$
Input:
arr = [0,1,2,3,4]
›
Output:
5
💡 Note:
Array is already sorted, so each element can be its own chunk: [0], [1], [2], [3], [4].
Constraints
- n == arr.length
- 1 ≤ n ≤ 10
- arr is a permutation of [0, 1, ..., n - 1]
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Permutation of integers [0, n-1] in some order
2
Find Chunks
Identify positions where we can split the array
3
Verify Result
Sorting each chunk and concatenating gives sorted array
Key Takeaway
🎯 Key Insight: We can end a chunk at position i when max(arr[0..i]) equals i, ensuring all elements 0 to i are present in the first i+1 positions.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code