Sponsored
Sponsored
This approach involves maintaining a running maximum for the left subarray and a suffix minimum for the right subarray. By iterating through the array and comparing these values, we can determine the appropriate partition point where all conditions are satisfied.
Time Complexity: O(n) - Linear scan of the array.
Space Complexity: O(1) - Only variables used for tracking, no extra storage required.
1function partitionDisjoint(nums) {
2 let maxLeft = nums[0];
3 let maxSoFar = nums[0];
4 let partitionIdx = 0;
5
6 for (let i = 1; i < nums.length; i++) {
7 if (nums[i] < maxLeft) {
8 maxLeft = maxSoFar;
9 partitionIdx = i;
10 } else {
11 maxSoFar = Math.max(maxSoFar, nums[i]);
12 }
13 }
14 return partitionIdx + 1;
15}
16
17console.log(partitionDisjoint([5, 0, 3, 8, 6])); // Output: 3
18
In JavaScript, the solution leverages running maximum values and selectively updates the partition index upon finding an element less than maxLeft
, ensuring partition criteria are followed.
This approach involves using two additional arrays: one to track the maximum values until any index from the left and another to track minimum values from the right. These auxiliary arrays help determine where a valid partition can be made in the original array.
Time Complexity: O(n) - Needs three linear passes through the array.
Space Complexity: O(n) - Additional space for two auxiliary arrays.
The Python solution applies two auxiliary arrays for managing maximum and minimum requirements for partitions, making it simple to compute the correct partition index.