
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find partition array into disjoint intervals in Python
Suppose we have an array nums, we have to partition it into two different subarrays called left and right such that −
Each element in left subarray is less than or equal to each element in right subarray.
left and right subarrays are non-empty.
left subarray has the smallest possible size.
We have to find the length of left after such a partitioning.
So, if the input is like nums = [5,0,3,8,6], then the output will be 3 because left array will be [5,0,3] and right subarray will be [8,6].
To solve this, we will follow these steps −
mx := null, temp := null, nmx := null
temp2 := 0
for each i in nums, do
if mx is same as null, then
mx := i
nmx := i
temp := temp2
temp2 := temp2 + 1
go for next iteration
if i>=mx, then
temp2 := temp2 + 1
if i>nmx, then
nmx := i
go for next iteration
otherwise,
temp := temp2
temp2 := temp2 + 1
mx := nmx
go for next iteration
return temp+1
Example
Let us see the following implementation to get better understanding −
def solve(nums): mx = None temp = None nmx = None temp2 = 0 for i in nums: if(mx==None): mx = i nmx = i temp = temp2 temp2+=1 continue if(i>=mx): temp2+=1 if(i>nmx): nmx = i continue else: temp = temp2 temp2+=1 mx = nmx continue return temp+1 nums = [5,0,3,8,6] print(solve(nums))
Input
[5,0,3,8,6]
Output
3
- Related Articles
- Partition Array into Disjoint Intervals in C++
- Maximal Disjoint Intervals in C++
- Program to find contiguous intervals of a unique array in Python
- Data Stream as Disjoint Intervals in C++
- Partition Array Into Three Parts With Equal Sum in Python
- Array Partition I in Python
- Program to partition color list in Python
- Program to find intervals by merging target interval in Python
- Program to partition two strings such that each partition forms anagram in Python
- Partition Array for Maximum Sum in Python
- Find a partition point in array in C++
- Find Intersecting Intervals in Python
- C++ Program to Find Maximum Number of Edge Disjoint Paths
- Program to find number of ways to split array into three subarrays in Python
- Program to find overlapping intervals and return them in ascending order in Python
