![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- if nums[i] is same as p, then
- 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
- if nums[i] < p, then
- 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
Advertisements