Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: arr = [5,4,3,2,1] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
Example 2:
Input: arr = [2,1,3,4,4] Output: 4 Explanation: We can split into two chunks, such as [2, 1], [3, 4, 4]. However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
Constraints:
1 <= arr.length <= 20000 <= arr[i] <= 108Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Stack · Greedy
[5,4,3,2,1]
[2,1,3,4,4]
max-chunks-to-make-sorted)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #768: Max Chunks To Make Sorted II
class Solution {
public int maxChunksToSorted(int[] arr) {
Deque<Integer> stk = new ArrayDeque<>();
for (int v : arr) {
if (stk.isEmpty() || stk.peek() <= v) {
stk.push(v);
} else {
int mx = stk.pop();
while (!stk.isEmpty() && stk.peek() > v) {
stk.pop();
}
stk.push(mx);
}
}
return stk.size();
}
}
// Accepted solution for LeetCode #768: Max Chunks To Make Sorted II
func maxChunksToSorted(arr []int) int {
var stk []int
for _, v := range arr {
if len(stk) == 0 || stk[len(stk)-1] <= v {
stk = append(stk, v)
} else {
mx := stk[len(stk)-1]
stk = stk[:len(stk)-1]
for len(stk) > 0 && stk[len(stk)-1] > v {
stk = stk[:len(stk)-1]
}
stk = append(stk, mx)
}
}
return len(stk)
}
# Accepted solution for LeetCode #768: Max Chunks To Make Sorted II
class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
stk = []
for v in arr:
if not stk or v >= stk[-1]:
stk.append(v)
else:
mx = stk.pop()
while stk and stk[-1] > v:
stk.pop()
stk.append(mx)
return len(stk)
// Accepted solution for LeetCode #768: Max Chunks To Make Sorted II
impl Solution {
pub fn max_chunks_to_sorted(arr: Vec<i32>) -> i32 {
let mut stk = Vec::new();
for &v in arr.iter() {
if stk.is_empty() || v >= *stk.last().unwrap() {
stk.push(v);
} else {
let mut mx = stk.pop().unwrap();
while let Some(&top) = stk.last() {
if top > v {
stk.pop();
} else {
break;
}
}
stk.push(mx);
}
}
stk.len() as i32
}
}
// Accepted solution for LeetCode #768: Max Chunks To Make Sorted II
function maxChunksToSorted(arr: number[]): number {
const stk: number[] = [];
for (let v of arr) {
if (stk.length === 0 || v >= stk[stk.length - 1]) {
stk.push(v);
} else {
let mx = stk.pop()!;
while (stk.length > 0 && stk[stk.length - 1] > v) {
stk.pop();
}
stk.push(mx);
}
}
return stk.length;
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.