Program to find max chunks to make array sorted in Python

Suppose we have an array nums, we have to split the array into some number of partitions, and individually sort each of them. After concatenating them we will get one sorted array. We have to find the maximum number of partitions we could have made?

So, if the input is like [3,2,4,5,5], then the output will be 4, as we can make partitions like [3,2], [4], [5], [5].

Algorithm

To solve this, we will follow these steps −

  • real := sort the list nums

  • p1 := 0, p2 := 1, c := 0

  • Do the following infinitely, do

    • flag := True

    • tmp := sort the sublist of nums[from index p1 to p2-1]

    • for j in range 0 to size of tmp, do

      • if tmp[j] is not same as real[p1+j], then

        • flag := False

        • p2 := p2 + 1

        • come out from loop

      • if flag is true, then

        • p1 := p2

        • p2 := p2+1

        • c := c + 1

      • if p1 is same as size of nums or p2 > size of nums, then

        • return c

Example

Let us see the following implementation to get better understanding ?

def solve(nums):
    real = sorted(nums)
    p1, p2, c = 0, 1, 0
    
    while True:
        flag = True
        tmp = sorted(nums[p1:p2])
        
        for j in range(len(tmp)):
            if tmp[j] != real[p1 + j]:
                flag = False
                p2 += 1
                break
        
        if flag:
            p1, p2 = p2, p2 + 1
            c += 1
            
        if p1 == len(nums) or p2 > len(nums):
            return c

nums = [3, 2, 4, 5, 5]
print(solve(nums))
4

How It Works

The algorithm works by comparing each potential partition with the corresponding elements in the sorted array. When a partition matches its expected position in the sorted array, we can safely make a cut there and continue with the next partition.

For the input [3, 2, 4, 5, 5]:

  • First partition [3, 2] when sorted becomes [2, 3], which matches positions 0-1 in sorted array [2, 3, 4, 5, 5]

  • Second partition [4] matches position 2

  • Third partition [5] matches position 3

  • Fourth partition [5] matches position 4

Conclusion

This approach finds the maximum number of partitions by incrementally checking if each subarray, when sorted, matches the corresponding elements in the fully sorted array. The time complexity is O(n²) due to the sorting operations within the loop.

Updated on: 2026-03-26T14:46:24+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements