Max Chunks To Make Sorted — LeetCode 769 Python Solution

MediumStackGreedyArraySortingMonotonic Stack
Problem
#769
Pattern
Stack
Reading time
2 min

The 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.

Example

Input
arr = [4,3,2,1,0]
Output
1
Explanation
Splitting into two or more chunks will not return the required result.

Python solution

Python
class Solution:
    def maxChunksToSorted(self, arr: List[int]) -> int:
        mx = ans = 0
        for i, v in enumerate(arr):
            mx = max(mx, v)
            if i == mx:
                ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 769. Max Chunks To Make Sorted is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 769. Max Chunks To Make Sorted?
LeetCode 769. Max Chunks To Make Sorted is rated Medium on LeetCode.
What topics does LeetCode 769. Max Chunks To Make Sorted cover?
LeetCode 769. Max Chunks To Make Sorted is tagged Stack, Greedy, Array, Sorting and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview