# 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum

Given an array of integers `arr` and an integer `target`.

You have to find two non-overlapping sub-arrays of `arr` each with sum equal `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:

```Input: arr = [3,2,2,4,3], target = 3
Output: 2
Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.
```

Example 2:

```Input: arr = [7,3,4,7], target = 7
Output: 2
Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
```

Example 3:

```Input: arr = [4,3,2,6,2,3,4], target = 6
Output: -1
Explanation: We have only one sub-array of sum = 6.
```

Example 4:

```Input: arr = [5,5,4,4,5], target = 3
Output: -1
Explanation: We cannot find a sub-array of sum = 3.
```

Example 5:

```Input: arr = [3,1,1,1,5,1,2,1], target = 3
Output: 3
Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.
```

Constraints:

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

Step 1: Here the idea is to use the sliding window, which moves from left to right, and keep track of the maximum sliding window size, whose element sum is = K, If the sum goes beyond K, shrink the window from left. If the Sum is less than k, then we use the previous window size, whose sum was k. At every index, we will store the maximum window size, whose element sum = k, into a prefix[] array

Step 2: We run another sliding window from right to left direction, keeping track of maximum sliding window size, whose elements sum is k. If the sum goes beyond K, shrink the window from the right. At every index, we will store the maximum window size, whose element sum = k, into a suffix[] array

Step 3: We traverse both prefix and suffix arrays together to find the maximum sum of elements in 2 arrays.

Runtime : O(N), Space O(N)

``````public int MinSumOfLengths(int[] arr, int target) {
//O(N), Space O(N)

int[] prefix = new int[arr.Length + 1]; //prefix[i] is the minimum length of sub-array ends before i and has sum = k,
int[] suffix = new int[arr.Length + 1]; //suffix[i] is the minimum length of sub-array starting at or after i and has sum = k.

//Base case -
prefix[0] = 0;
suffix[suffix.Length - 1] = 0;

int start = 1;
int currSum = 0;
for (int i = start; i < arr.Length; i++)
{
currSum += arr[i - 1];

//sliding widnow - shrinks from left side, if currSum > target
while (currSum > target)
{
currSum -= arr[start - 1];
start += 1;
}

if (currSum == target)
{
//i - start + 1 --> this is the range that makes sum = target
prefix[i] = (prefix[i - 1] > 0) ? Math.Min(i - start + 1, prefix[i - 1]) : i - start + 1;
}
else
{
//Pick the previous Min value
prefix[i] = prefix[i - 1];
}
}

//sliding widnow - shrinks from right side, if currSum > target
currSum = 0;
start = suffix.Length - 2;
for (int i = start; i >= 0 ; i--)
{
while (currSum > target)
{
currSum -= arr[start];
start -= 1;
}

if (currSum == target)
{
//start - i --> this is the range that makes sum = target
suffix[i] = (suffix[i + 1] > 0) ? Math.Min(start - i, suffix[i + 1]) : start - i;
}
else
{
//Pick the previous Min value, But as we are sliding width from right to left... our previous value exist on right side
suffix[i] = suffix[i + 1];
}

//This is the suffix sum... So We are not including the current element first...
currSum += arr[i];
}

//Working with the idea that a non overlapping subarray lies to right and left of an index,
//so we select minimum subarray from the two halves of the array.
int minComb = int.MaxValue;
for (int i = 1; i < suffix.Length; i++)
{
if (prefix[i] == 0 || suffix[i - 1] == 0)
continue;

minComb = Math.Min(minComb, prefix[i] + suffix[i - 1]);
}
return (minComb == int.MaxValue) ? -1 : minComb;
}``````

## 5,583 thoughts on “1477. Find Two Non-overlapping Sub-arrays Each With Target Sum”

1. binsina pharmacy coupon drug store discounts for seniors

10% OFF VOUCHER February 2022 for OpenMedShop OPENMEDSHOP.COM is:
MEDS10

mulligans pharmacy discount code cara pharmacy gift card

2. How much of a discount do Nike employees get?
How do I use my NHS discount online at Morrisons?

February 2022 OpenMedShop openmedshop.com 10% OFF voucher:
MEDS10

How do I use my Kate Spade student discount online?
Is Blue Light Card same as Defence discount card?

3. Are there Mastercard Gift Cards? delivery pharmacy discount code

10% OFF March 2022 VOUCHER for ApprovedNets http://approvednets.com is:
ANET10

covetrus pharmacy coupon Does Yeti do student discount?

5. vitacost coupon code Can you use Michaels coupons at Joann Fabrics?

10% OFF March 2022 VOUCHER CODE for ApprovedNets APPROVEDNETS.COM is: ANET10

Does Currys do NHS student discount? gift card exchange

6. Does Tesco support the Blue Light Card? Does Applebees
have a student discount?

10% OFF March 2022 COUPON CODE for ApprovedNets APPROVEDNETS.COM is: ANET10

Does on running have discounts? How do you get your
NUS card?

7. I like the efforts you have put in this, thankyou for all the great posts.

8. instagram hacklink hizmetleri satın alarak sosyal medyanızı büyütün.

9. instagram hacklink hizmetleri satın alarak sosyal medyanızı büyütün.

10. Appreciate it for this post, I am a big fan of this internet site would like to proceed updated.

11. Thanks a lot for sharing this with all people you really realize what you are speaking approximately! Bookmarked. Please also talk over with my website =). We could have a hyperlink trade agreement among us!

12. Hi, Neat post. There’s an issue along with your site in web explorer, could check this… IE nonetheless is the marketplace chief and a big element of people will miss your magnificent writing because of this problem.

13. [url=https://sildenafil2022.com/]best generic sildenafil[/url]

14. Fantastic web site. Lots of useful information here. I’m sending it to some buddies ans additionally sharing in delicious. And naturally, thanks to your effort!

15. Omegla sohbet, omegle chat odaları ve ome tv sohbet rastgele görüntülü kameralı chat ometv sohbet imkanı sunar.

16. bedava sohbet , chat sohbet odaları, mobil uyumlu chat arayüzü, omegle chat, ometv ile HASRET sohbet keyfini sizlere sunuyor.

17. Mobil sohbet odaları ile bedava sohbet chat yapabilirsiniz. Sohbet siteleri içerisinde en beğenilen sohbet kanallarına hemen giriş yap!

18. I love it when people come together and share opinions, great blog, keep it up

19. Fantastic web site. Lots of useful information here. I’m sending it to some buddies ans additionally sharing in delicious. And naturally, thanks to your effort!

20. Steroid terimi vücutta ki bir hormonun adıdır. kullanmak için steroid satın al ile arama yapan kullanıcıların en doğru şekilde bilgi edinmesi bizim görevimizdir.

21. What i do not realize is actually how you are not actually much more well-liked than you might be now. You are very intelligent. You realize therefore considerably relating to this subject, made me personally consider it from numerous varied angles. Its like men and women aren’t fascinated unless it is one thing to accomplish with Lady gaga! Your own stuffs excellent. Always maintain it up!

22. A very successful work. Congratulations, take care of yourself. https://steroidmagazan.com Geniş kadrosu ile kurulduğu dönemden beri steroid satın al konusunda güvenli bir alışveriş imkânı sunuyor. Hedefimiz, Yurtiçi ve Yurtdışı kaynaklar ile bu sektörde bulunduğumuz liderlik konumumuzu korumak.

23. I’d have to examine with you here. Which is not one thing I usually do! I take pleasure in reading a post that may make folks think.

24. Bu çerçevede steroid kür satın al çözümleri sayesinde kusursuz bir seçimden faydalanmanız mümkün!

25. I would like to thnkx for the efforts you have put in writing this blog.

26. It is really a great and useful piece of information. I’m glad that you simply shared this useful info with us. Please keep us up to date like this. Thanks for sharing

27. Everything you are looking for chat, friendship and dating is available on this mobile chat platform.

28. We are here to offer the best mobile chat applications with a unique user experience and always be with you.

29. mobil ödeme bozdurma sitesi üzerinden faturalı veya faturasız hattınızı kullanarak kazanç elde etmeniz mümkün. Şöyle ki; bu siteler telefonunuza bir SMS gönderiyor. Gelen SMS’e onay vermeniz hâlinde hattınızdaki TL bakiyesi karşılığı nakit ödeme alıyorsunuz. Yahut, size ödenecek ücret ay sonu faturanıza yansıtılıyor.

30. It is really a great and useful piece of information. I’m glad that you simply shared this useful info with us. Please keep us up to date like this. Thanks for sharing

31. What i do not realize is actually how you are not actually much more well-liked than you might be now. You are very intelligent. You realize therefore considerably relating to this subject, made me personally consider it from numerous varied angles. Its like men and women aren’t fascinated unless it is one thing to accomplish with Lady gaga! Your own stuffs excellent. Always maintain it up!

32. I’ve been exploring for a little for any high quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this web site. Reading this info So i’m happy to convey that I have a very good uncanny feeling I discovered just what I needed. I most certainly will make sure to do not forget this web site and give it a look on a constant basis.

33. Çorlu’da elbette ki birçok el ikinci el eşya alım satımı yapan firma bulunmaktadır. Ancak aynı zamanda çok sayıda kuruluş bulunmaktadır.

34. Bot says: