You get an array of whole numbers, arr, which may contain repeats. Cut it into consecutive pieces, called chunks. Sort each chunk on its own, then join the chunks back in their original order.
The cut is valid when the joined result equals arr sorted. Return the largest number of chunks a valid cut can have.
Example 1
Input: arr = [1, 3, 2, 4, 0, 6] Output: 2 Why: the 0 must reach the front, so [1, 3, 2, 4, 0] stays whole; [6] is apart
2 more examples and the constraints
Example 2
Input: arr = [2, 2, 1, 4, 4] Output: 3 Why: [2, 2, 1] | [4] | [4]
Example 3
Input: arr = [9, 7, 5] Output: 1 Why: 5 must move to the front, past every other value
Constraints
- 1 ≤ length of arr ≤ 2,000
- Every value is between 0 and 100,000,000
- Values can repeat
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)
- Prefix max vs suffix minO(n)
- Monotonic stack of chunk maxesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 2,000 numbers | Verdict |
|---|---|---|---|
| Sort every prefix | O(n² log n) | Right test, repeated work | |
| Prefix max vs suffix min | O(n) | Passes; two passes | |
| Monotonic stack of chunk maxes | O(n) | Best; one pass |
n = length of arr.
Edge cases to test
- Already sorted. [0, 1, 2, 3, 4] gives 5: every value is its own chunk.
- Strictly decreasing. [9, 7, 5] gives 1: the whole array is one chunk.
- All values equal. [4, 4, 4, 4] gives 4, which needs ≤ (not <) in the comparisons.
- A small value at the end. [5, 6, 7, 1] gives 1: the 1 merges every chunk.
- One element. [3] gives 1.
Common mistakes
- Using the trick from the version without repeats (max equals index), which breaks once values repeat.
- Comparing with < instead of ≤, so equal values are wrongly forced into one chunk.
- Forgetting to push
headback after merging, which loses the merged chunk.
How to talk through it
- 1Clarify. Can values repeat? Must the chunks be consecutive? Is one chunk always allowed?
- 2Give the brute force. A cut fits after k items when the sorted prefix matches the sorted array's prefix.
- 3Turn it into max and min. That match holds exactly when max(left) ≤ min(right).
- 4Code the stack. Keep chunk maxes increasing; a small value pops and merges, then the head goes back.
- 5Test out loud. Run all-equal, sorted and a small last value before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?