#915

Partition Array into Disjoint Intervals

Medium
ArrayTwo PointersArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a single pass to find the partition point by keeping track of the maximum value in the left subarray and the minimum value in the right subarray. This allows us to find the partition efficiently without nested loops.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to keep track of the maximum value of the left subarray.
  2. 2Step 2: Iterate through the array, updating the maximum value and checking if the current element is less than or equal to the minimum value of the right subarray.
  3. 3Step 3: When the condition is satisfied, return the current index + 1 as the size of the left subarray.
solution.py14 lines
1# Full working Python code
2
3def partition_disjoint(nums):
4    left_max = nums[0]
5    partition_index = 0
6    for i in range(1, len(nums)):
7        if nums[i] < left_max:
8            partition_index = i
9        else:
10            left_max = max(left_max, nums[i])
11    return partition_index + 1
12
13# Example usage
14print(partition_disjoint([5,0,3,8,6]))  # Output: 3

Complexity note: The time complexity is O(n) because we only make a single pass through the array, updating our maximum and checking conditions without any nested loops.

  • 1The maximum value of the left subarray must always be less than or equal to the minimum value of the right subarray.
  • 2The partition point must be found efficiently to avoid unnecessary computations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.