Similar Problems
Similar Problems not available
Partition Array Into Disjoint Intervals - Leetcode Solution
Companies:
LeetCode: Partition Array Into Disjoint Intervals Leetcode Solution
Difficulty: Medium
Topics: array
Problem Statement: Given an 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.
- Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example:
Input: nums = [5,0,3,8,6] Output: 3 Explanation: left = [5,0,3], right = [8,6]
Solution: To solve this problem, we need to find the length of the first contiguous subarray that satisfies the above conditions. We can do this by first calculating the maximum element from 0th index to i-th index for every i. Similarly, we can calculate the minimum element from n-1th index to i-th index for every i. Then we can iterate through 0 to n-2 index to find the position where maximum element so far is less than or equal to minimum element from the next index to n-1 index. This position gives us the end of the first contiguous subarray that satisfies the conditions. The length of this subarray is then returned as the answer.
Here's the Python code:
def partitionDisjoint(nums): n = len(nums) max_so_far = float('-inf') max_list = [] for i in range(n): max_so_far = max(max_so_far, nums[i]) max_list.append(max_so_far)
min_so_far = float('inf')
min_list = []
for i in range(n-1, -1, -1):
min_so_far = min(min_so_far, nums[i])
min_list.append(min_so_far)
min_list.reverse()
for i in range(n-1):
if max_list[i] <= min_list[i+1]:
return i+1
Test the function
nums = [5,0,3,8,6] print(partitionDisjoint(nums))
Output: 3
Partition Array Into Disjoint Intervals Solution Code
1