Partition Array into Disjoint Intervals - Problem
Given an integer array nums, you need to partition it into two contiguous subarrays called left and right such that:
- Every element in
leftis less than or equal to every element inright - Both
leftandrightare non-empty lefthas the smallest possible size
Your task is to return the length of the left subarray after such partitioning.
Example: For array [5,0,3,8,6], we can partition it as left = [5,0,3] and right = [8,6]. The maximum in left (5) โค minimum in right (6), and left has minimum possible size of 3.
Input & Output
example_1.py โ Basic Case
$
Input:
[5,0,3,8,6]
โบ
Output:
3
๐ก Note:
We partition into left=[5,0,3] and right=[8,6]. The maximum in left (5) โค minimum in right (6), and this gives the smallest possible left partition.
example_2.py โ Already Sorted
$
Input:
[1,1,1,2]
โบ
Output:
1
๐ก Note:
We can partition into left=[1] and right=[1,1,2]. The maximum in left (1) โค minimum in right (1), giving the minimum left size of 1.
example_3.py โ Large Left Required
$
Input:
[1,1,1,0,6,12]
โบ
Output:
4
๐ก Note:
Due to the 0 in position 3, we need left=[1,1,1,0] and right=[6,12]. The maximum in left (1) โค minimum in right (6).
Constraints
- 2 โค nums.length โค 105
- 0 โค nums[i] โค 106
- A valid partitioning always exists
Visualization
Tap to expand
Understanding the Visualization
1
Build prefix maximums
For each position i, store the maximum element from start to i
2
Build suffix minimums
For each position i, store the minimum element from i to end
3
Find partition point
Look for first position where prefix_max[i] โค suffix_min[i+1]
4
Return result
The partition point + 1 gives us the length of the left subarray
Key Takeaway
๐ฏ Key Insight: We need to find the earliest position where the maximum element on the left is โค minimum element on the right, which can be efficiently computed using prefix maximums and suffix minimums.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code