# Program to find two non-overlapping sub-arrays each with target sum using Python

Suppose we have an array of arr and another value target. We have to find two non-overlapping sub-arrays of arr where each has sum equal to target. If there are multiple answers, then we have to find an answer where the sum of the lengths of the two sub-arrays is smallest. We have to find the minimum sum of the lengths of the two required sub-arrays, if there is no such subarray then return -1.

So, if the input is like arr = [5,2,6,3,2,5] target = 5, then the output will be 2 there are three subarrays with sum 5, they are [5], [3,2] and [5], now among them only two have smallest size.

To solve this, we will follow these steps −

• ans := infinity

• best := make an array whose size is same as arr and fill with infinity

• prefix := 0

• latest := a map where store -1 for key 0

• for each index i and value x of arr, do

• prefix := prefix + x

• if (prefix - target) is present in latest, then

• ii := latest[prefix - target]

• if ii >= 0, then

• ans := minimum of ans and (i - ii + best[ii])

• best[i] := i - ii

• if i is non-zero, then

• latest[prefix] := i

• return ans if ans < 999999 otherwise -1

Let us see the following implementation to get better understanding −

## Example

Live Demo

def solve(arr, target):
ans = 999999
best = [999999]*len(arr)
prefix = 0
latest = {0: -1}
for i, x in enumerate(arr):
prefix += x
if prefix - target in latest:
ii = latest[prefix - target]
if ii >= 0:
ans = min(ans, i - ii + best[ii])
best[i] = i - ii
if i: best[i] = min(best[i-1], best[i])
latest[prefix] = i
return ans if ans < 999999 else -1
arr = [5,2,6,3,2,5]
target = 5
print(solve(arr, target))

## Input

[5,2,6,3,2,5], 5

## Output

2