Program to find minimum length of first split of an array with smaller elements than other list in Python

Suppose we have a list of numbers nums, we want to split the list into two parts part1 and part2 such that every element in part1 is less than or equal to every element in part2. We have to find the smallest length of part1 that is possible (not 0 length).

So, if the input is like nums = [3, 1, 2, 5, 4], then the output will be 3, because we can split the list like part1 = [3, 1, 2] and part2 = [5, 4].

Algorithm Approach

To solve this problem, we follow these steps ?

  • p := minimum of nums
  • s := 0
  • for i in range 0 to size of nums - 1, do
    • if nums[i] is same as p, then
      • s := i
      • break from the loop
  • p := maximum of the sub-list of nums[from index 0 to s]
  • ans := s
  • for i in range s + 1 to size of nums - 1, do
    • if nums[i] < p, then
      • ans := i
  • return ans + 1

Example

Let us see the following implementation to get better understanding ?

def solve(nums):
    p = min(nums)
    s = 0
    for i in range(len(nums)):
        if nums[i] == p:
            s = i
            break
    p = max(nums[: s + 1])
    ans = s
    for i in range(s + 1, len(nums)):
        if nums[i] < p:
            ans = i
    return ans + 1

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

How It Works

The algorithm works in two phases:

  1. Find the minimum element's first position: This ensures that all elements before this position plus the minimum element can potentially form part1.
  2. Extend the split point: We find the maximum element in the current part1, then check if any remaining elements are smaller than this maximum. If so, they must also be included in part1.

Additional Example

Let's test with another example to better understand the logic ?

def solve(nums):
    p = min(nums)
    s = 0
    for i in range(len(nums)):
        if nums[i] == p:
            s = i
            break
    p = max(nums[: s + 1])
    ans = s
    for i in range(s + 1, len(nums)):
        if nums[i] < p:
            ans = i
    return ans + 1

# Test with different examples
test_cases = [
    [3, 1, 2, 5, 4],
    [1, 2, 3, 4, 5],
    [5, 4, 3, 2, 1]
]

for nums in test_cases:
    result = solve(nums)
    print(f"Input: {nums}, Minimum split length: {result}")
Input: [3, 1, 2, 5, 4], Minimum split length: 3
Input: [1, 2, 3, 4, 5], Minimum split length: 1
Input: [5, 4, 3, 2, 1], Minimum split length: 5

Conclusion

This algorithm efficiently finds the minimum split length by first locating the minimum element's position, then extending the split point to ensure all smaller elements are included in the first part. The time complexity is O(n) where n is the length of the array.

Updated on: 2026-03-26T17:36:57+05:30

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements