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
๐Ÿดโ€โ˜ ๏ธ Treasure Hunter's Optimal StrategyGold!Size: 1Bigger DepositSize: 3Gold!Size: 1Smart TrackingBest site before pos 4: Size 1Current site: Size 1Total: 1 + 1 = 2 โœ“Sliding WindowEfficiently finds depositsAvoids redundant diggingO(n) time complexity๐Ÿ’ก Key InsightDP + Sliding Window = Real-time Optimal PairingTrack best previous + find current efficiently
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.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
52.5K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen