Find Two Non-overlapping Sub-arrays Each With Target Sum

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.

Example 1
Inputarr = [3,2,2,4,3], target = 3
Output2
Only two sub-arrays have sum = 3 ([3] and [3]), and the sum of their lengths is 2.
Example 2
Inputarr = [7,3,4,7], target = 7
Output2
Although there are three non-overlapping sub-arrays of sum = 7 ([7], [3,4], and [7]), choosing the first and third gives the minimum total length of 2.

Constraints

  • 1 <= arr.length <= 10^5
  • 1 <= arr[i] <= 1000
  • 1 <= target <= 10^8

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate