Partition Array into Disjoint Intervals - Problem

Given an integer array nums, partition it into two contiguous subarrays left and right so that:

  • Every element in left is less than or equal to every element in right.
  • left and right are non-empty.
  • left has the smallest possible size.

Return the length of left after such a partitioning.

Test cases are generated such that partitioning exists.

Input & Output

Example 1 — Basic Partition
$ Input: nums = [5,0,3,8,6]
Output: 3
💡 Note: Partition into left=[5,0,3] and right=[8,6]. Max of left is 5, min of right is 6. Since 5 ≤ 6, this is valid. Length of left is 3.
Example 2 — All Left Except Last
$ Input: nums = [1,1,1,2]
Output: 3
💡 Note: Partition into left=[1,1,1] and right=[2]. Max of left is 1, min of right is 2. Since 1 ≤ 2, this is valid. Length of left is 3.
Example 3 — Minimum Valid Partition
$ Input: nums = [1,2]
Output: 1
💡 Note: Partition into left=[1] and right=[2]. Max of left is 1, min of right is 2. Since 1 ≤ 2, this is valid. Length of left is 1.

Constraints

  • 2 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Partition Array into Disjoint Intervals INPUT nums array: 5 i=0 0 i=1 3 i=2 8 i=3 6 i=4 Goal: Find partition point where max(left) <= min(right) with smallest left size Variables: maxLeft, maxSoFar, partLen Length = 5 elements ALGORITHM STEPS 1 Initialize maxLeft=nums[0]=5 maxSoFar=5, partLen=1 2 Iterate i=1 to n-1 Update maxSoFar = max (maxSoFar, nums[i]) 3 Check Condition If nums[i] < maxLeft: maxLeft=maxSoFar, partLen=i+1 4 Return partLen Smallest left partition Trace: i=1: 0<5 --> maxL=5, len=2 i=2: 3<5 --> maxL=5, len=3 i=3: 8>=5 --> no change i=4: 6>=5 --> no change Result: partLen = 3 FINAL RESULT Partitioned Array: LEFT (length=3) 5 0 3 RIGHT 8 6 Verification: max(left) = max(5,0,3) = 5 min(right) = min(8,6) = 6 5 <= 6 [OK] OUTPUT 3 Length of left partition (smallest possible) Key Insight: Track two values: maxLeft (max of left partition) and maxSoFar (max seen so far). When nums[i] < maxLeft, the element must be included in left partition, so update partition length and maxLeft. This ensures we find the smallest left partition in O(n) time with O(1) space - a single pass solution! TutorialsPoint - Partition Array into Disjoint Intervals | Optimized Single Pass Approach
Asked in
Google 42 Facebook 38 Microsoft 31 Amazon 29
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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