DIY: Find Two Non-Overlapping Subarrays Each with Target Sum

Solve the interview question "Find Two Non-Overlapping Subarrays Each with Target Sum" in this lesson.

Problem statement

In this challenge, you are given an array of integers named arr and an integer named target. Your task is to find two non-overlapping subarrays in arr such that both subarrays have a sum equal to the target. The output should be the sum of the lengths of the two required subarrays or -1 if two such subarrays do not exist.

Note: There can be multiple answers, so you have to find an answer where the sum of the lengths of the two subarrays is minimum.

Input

The inputs are an array of integers named arr and an integer value named target. The following is an example of the inputs:

arr = {3,1,1,1,5,1,2,1}
target = 3

Output

The output will be an integer that represents the sum of minimum length subarray, each with the required target sum. The output for the inputs mentioned above is as follows:

3

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.