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
Max Chunks To Make Sorted INPUT Array arr (permutation of 0 to n-1) 4 i=0 3 i=1 2 i=2 1 i=3 0 i=4 Input: arr = [4, 3, 2, 1, 0] n = 5 Sorted should be: [0, 1, 2, 3, 4] Array is in descending order! ALGORITHM STEPS 1 Initialize max_so_far = 0, chunks = 0 2 Iterate through array Track max element seen 3 Check if max == index If true, increment chunks 4 Return chunks count Total valid partitions Iteration Trace: i=0: max=4, 4!=0 [NO] i=1: max=4, 4!=1 [NO] i=2: max=4, 4!=2 [NO] i=3: max=4, 4!=3 [NO] i=4: max=4, 4==4 [OK] chunks = 1 FINAL RESULT Only 1 chunk possible: Chunk 1 [4, 3, 2, 1, 0] entire array sort [0, 1, 2, 3, 4] Output 1 OK - Maximum chunks = 1 Key Insight: A chunk can end at index i only when max(arr[0..i]) == i. This means all elements from 0 to i are present in arr[0..i], so sorting this chunk places them correctly. For [4,3,2,1,0], the max element 4 only equals its index at i=4, so only 1 chunk works. TutorialsPoint - Max Chunks To Make Sorted | Greedy - Track Maximum Element
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
89.4K Views
Medium Frequency
~15 min Avg. Time
2.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