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 left is less than or equal to every element in right
  • Both left and right are non-empty
  • left has 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
Partition Array: [5,0,3,8,6]Original:50386Prefix Max:55588Suffix Min:00366Check:5 > 0 โœ—5 > 0 โœ—5 โ‰ค 6 โœ“Left PartitionRight PartitionAnswer: 3 (length of left partition)
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.
Asked in
Google 42 Amazon 35 Microsoft 28 Facebook 22
42.8K Views
Medium-High Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen