LeetCode 1477: Find Two Non-overlapping Sub-arrays Each With Target Sum Solution
Master LeetCode problem 1477 (Find Two Non-overlapping Sub-arrays Each With Target Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1477. Find Two Non-overlapping Sub-arrays Each With Target Sum
Problem Explanation
Explanation:
To solve this problem, we can use a two-pointer technique combined with prefix sums. We iterate through the array and calculate the prefix sum at each index. Then, we iterate through the array again and for each index, we find the length of the subarray with sum equal to the target from the left end. We store these lengths in an array.
Next, we iterate through the array in reverse and for each index, we find the length of the subarray with sum equal to the target from the right end. We store these lengths in another array.
Finally, we iterate through both arrays and find the minimum sum of lengths of the two non-overlapping subarrays with the target sum.
:
Solution Code
class Solution {
public int minSumOfLengths(int[] arr, int target) {
int n = arr.length;
int[] leftSum = new int[n];
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int sum = 0, minLen = Integer.MAX_VALUE, result = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
sum += arr[i];
leftSum[i] = minLen;
if (map.containsKey(sum - target)) {
int len = i - map.get(sum - target);
minLen = Math.min(minLen, len);
}
map.put(sum, i);
}
map.clear();
map.put(0, n);
sum = 0;
for (int i = n - 1; i >= 0; i--) {
sum += arr[i];
if (map.containsKey(sum - target)) {
int len = map.get(sum - target) - i;
if (len + leftSum[i] < result) {
result = len + leftSum[i];
}
}
if (i > 0) {
map.put(sum, i);
}
}
return result == Integer.MAX_VALUE ? -1 : result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1477 (Find Two Non-overlapping Sub-arrays Each With Target Sum)?
This page provides optimized solutions for LeetCode problem 1477 (Find Two Non-overlapping Sub-arrays Each With Target Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1477 (Find Two Non-overlapping Sub-arrays Each With Target Sum)?
The time complexity for LeetCode 1477 (Find Two Non-overlapping Sub-arrays Each With Target Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1477 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1477 in Java, C++, or Python.