Find Two Non-overlapping Sub-arrays Each With Target Sum - Problem
You're given an array of integers arr and a target integer target. Your mission is to find two non-overlapping subarrays where each subarray has a sum exactly equal to target.
Here's the twist: there might be multiple valid combinations, but you need to find the one where the total length of both subarrays combined is minimum.
Goal: Return the minimum sum of lengths of two required subarrays, or -1 if no such pair exists.
Example: If arr = [3,2,2,4,3] and target = 3, you could choose subarrays [3] (length 1) and [3] (length 1) for a total length of 2.
Input & Output
example_1.py โ Basic Case
$
Input:
arr = [3,2,2,4,3], target = 3
โบ
Output:
2
๐ก Note:
We can choose subarrays [3] (at index 0) and [3] (at index 4). Both have length 1, so total length is 2.
example_2.py โ Multiple Valid Pairs
$
Input:
arr = [7,3,4,7], target = 7
โบ
Output:
2
๐ก Note:
We can choose subarrays [7] (at index 0) and [7] (at index 3). Both have length 1, so total length is 2.
example_3.py โ No Valid Solution
$
Input:
arr = [4,3,2,6,2,3,4], target = 6
โบ
Output:
-1
๐ก Note:
We can find [6] and [2,3] and [3] but we need exactly two non-overlapping subarrays. The only subarray with sum 6 is [6] itself, so we cannot find two non-overlapping subarrays.
Constraints
- 1 โค arr.length โค 105
- 1 โค arr[i] โค 1000
- 1 โค target โค 108
- All array elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Scan with Smart Window
Use a sliding window to efficiently find gold deposits (subarrays with target sum)
2
Track Best Sites
Maintain a record of the shortest mining site found before each position
3
Real-time Optimization
When finding a new site, immediately check if it can pair optimally with previous sites
Key Takeaway
๐ฏ Key Insight: By combining dynamic programming (to track optimal previous solutions) with sliding window (to find current solutions efficiently), we achieve optimal O(n) time complexity while making the best pairing decisions in real-time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code