Max Chunks To Make Sorted II - Problem

You are given an integer array arr. 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 — Basic Case
$ Input: arr = [5,4,3,2,1]
Output: 1
💡 Note: The array is already in reverse order. No matter how we split it, we need all elements together to form the sorted sequence [1,2,3,4,5]. Only 1 chunk is possible.
Example 2 — Multiple Chunks Possible
$ Input: arr = [2,1,3,4,4]
Output: 4
💡 Note: We can split as [2,1] | [3] | [4] | [4]. After sorting each chunk: [1,2] + [3] + [4] + [4] = [1,2,3,4,4], which matches the sorted array.
Example 3 — Already Sorted
$ Input: arr = [1,2,3,4,5]
Output: 5
💡 Note: Array is already sorted, so we can make each element its own chunk: [1] | [2] | [3] | [4] | [5]. Maximum possible chunks.

Constraints

  • 1 ≤ arr.length ≤ 2000
  • 0 ≤ arr[i] ≤ 108

Visualization

Tap to expand
Max Chunks To Make Sorted IIInput Array:21344Optimal Chunks:[2,1][3][4][4]↓ Sort each chunk individually ↓[1,2][3][4][4]↓ Concatenate sorted chunks ↓Final Result:12344= Sorted Array ✓Answer: 4 chunks
Understanding the Visualization
1
Input Array
Given array that needs to be partitioned
2
Find Partitions
Identify positions where we can safely split the array
3
Sort and Verify
Each chunk sorts to correct position in final array
Key Takeaway
🎯 Key Insight: We can safely split after position i if all elements in positions 0 to i belong to the first i+1 positions in the sorted array
Asked in
Google 42 Amazon 28 Facebook 15 Microsoft 12
89.3K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen