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
Find Two Non-overlapping Sub-arrays Each With Target Sum INPUT Array: arr 3 i=0 2 i=1 2 i=2 4 i=3 3 i=4 Target Sum 3 Find 2 non-overlapping sub-arrays with sum = 3 Minimize total length ALGORITHM STEPS 1 Prefix Sum + HashMap Store prefix sums to find sub-arrays with target sum 2 Track Min Length minLen[i] = shortest valid sub-array ending at or before i 3 Combine Two Sub-arrays For each valid sub-array, add minLen before its start 4 Find Minimum Sum Track global minimum of combined lengths Valid Sub-arrays Found: [3] at i=0, len=1 [3] at i=4, len=1 (non-overlapping pair) FINAL RESULT Two Non-overlapping Sub-arrays: 3 2 2 4 3 Sub-array 1 Sub-array 2 Length Calculation: [3] --> length = 1 [3] --> length = 1 Total = 1 + 1 = 2 Output 2 OK - Minimum sum found! Key Insight: Use prefix sums with a HashMap to find all sub-arrays with the target sum in O(n). Maintain minLen[i] to track the minimum length of valid sub-arrays ending at or before index i. For each new valid sub-array found, combine its length with minLen[start-1] to ensure non-overlapping. Time: O(n), Space: O(n). TutorialsPoint - Find Two Non-overlapping Sub-arrays Each With Target Sum | Optimal Solution
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
24.5K Views
Medium Frequency
~25 min Avg. Time
890 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