Find Two Non-overlapping Sub-arrays Each With Target Sum - Problem
You are given an array of integers arr and an integer target.
You have to find two non-overlapping sub-arrays of arr each with a sum equal to target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [3,2,2,4,3], target = 3
›
Output:
2
💡 Note:
Only sub-arrays with sum 3 are [3] at index 0 and [3] at index 4. Total length = 1 + 1 = 2.
Example 2 — Multiple Options
$
Input:
arr = [7,3,4,7], target = 7
›
Output:
2
💡 Note:
Sub-arrays with sum 7: [7] at index 0 (length 1), [3,4] at indices 1-2 (length 2), [7] at index 3 (length 1). Best pair: [7] + [7] = 1 + 1 = 2.
Example 3 — No Solution
$
Input:
arr = [1,1,1,1], target = 3
›
Output:
-1
💡 Note:
Sub-arrays with sum 3: [1,1,1] at indices 0-2 and [1,1,1] at indices 1-3. These overlap, so no valid pair exists.
Constraints
- 1 ≤ arr.length ≤ 1000
- 1 ≤ arr[i] ≤ 1000
- 1 ≤ target ≤ 300
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Array [3,2,2,4,3] with target sum 3
2
Find Valid Sub-arrays
Identify all sub-arrays that sum to target: [3] at index 0, [3] at index 4
3
Check Non-overlapping
Verify the sub-arrays don't share any indices and return minimum total length
Key Takeaway
🎯 Key Insight: Use sliding window with prefix tracking to efficiently find valid sub-arrays while maintaining information about the best previous options for optimal pairing.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code