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.
#include <vector>
#include <climits>
using namespace std;
int partitionDisjoint(vector<int>& nums) {
int n = nums.size();
vector<int> leftMax(n), rightMin(n);
leftMax[0] = nums[0];
for (int i = 1; i < n; ++i) {
leftMax[i] = max(nums[i], leftMax[i - 1]);
}
rightMin[n - 1] = nums[n - 1];
for (int i = n - 2; i >= 0; --i) {
rightMin[i] = min(nums[i], rightMin[i + 1]);
}
for (int i = 0; i < n - 1; ++i) {
if (leftMax[i] <= rightMin[i + 1]) {
return i + 1;
}
}
return n;
}
int main() {
vector<int> nums = {5, 0, 3, 8, 6};
cout << partitionDisjoint(nums) << endl; // Output: 3
return 0;
}
The C++ approach maintains two arrays for maximum from the left and minimum from the right. These arrays are indexed to find the partition point whereby elements in leftMax
are always lesser or equal to those in rightMin
at a determined boundary.