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 part1. 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].

To solve this, we will 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
      • come out 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))

Input

[3, 1, 2, 5, 4]

Output

3

Updated on: 19-Oct-2021

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements