arr holds each number from 0 to n − 1 exactly once, in some order.
Cut arr into consecutive pieces, sort each piece on its own, and glue the pieces back together in the same order. The glued result must be fully sorted.
Return the largest number of pieces you can cut it into.
Example 1
Input: arr = [2, 0, 1, 4, 3, 5] Output: 3 Why: [2, 0, 1] [4, 3] [5] each sort into place
2 more examples and the constraints
Example 2
Input: arr = [3, 0, 1, 2] Output: 1 Why: 3 must move to the end, so no cut works
Example 3
Input: arr = [0, 2, 1, 3] Output: 3 Why: [0] [2, 1] [3]
Constraints
- 1 ≤ n ≤ 10
- 0 ≤ arr[i] < n
- Every value appears once (arr is a permutation of 0 to n − 1)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort every prefixO(n² log n)
- Running maximumO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10 elements | Verdict |
|---|---|---|---|
| Sort every prefix | O(n² log n) | Correct; repeats work | |
| Running maximum | O(n) | Best; one pass |
n = length of arr.
Edge cases to test
- One element. [0] gives 1.
- Already sorted. [0, 1, 2, 3] gives 4: every gap is a cut.
- Fully reversed. [3, 2, 1, 0] gives 1: the max reaches n − 1 at once.
- Largest value first. Any array starting with n − 1 gives 1.
Common mistakes
- Comparing arr[i] with i instead of the running max: [1, 0] never has arr[i] = i, yet it is one chunk.
- Starting the max at 0 and the loop at 1, which skips the cut after index 0.
- Counting cuts between elements and forgetting the last piece, which is off by one.
How to talk through it
- 1Clarify. Is arr always a permutation of 0..n−1? Must the pieces stay in order?
- 2State the cut rule. A cut after i is safe when the prefix holds exactly 0..i.
- 3Give the slow check. Sort each prefix and compare: O(n² log n).
- 4Shrink the check. The prefix is 0..i exactly when its max is i; keep a running max.
- 5Test out loud. Run the sorted, reversed and single-element cases.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?