Find Two Non-overlapping Sub-arrays Each With Target Sum — LeetCode 1477 Python Solution
MediumArrayHash TableBinary SearchDynamic ProgrammingSliding Window
- Problem
- #1477
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The 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 target.
Example
- 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.
Python solution
Python
class Solution:
def minSumOfLengths(self, arr: List[int], target: int) -> int:
d = {0: 0}
s, n = 0, len(arr)
f = [inf] * (n + 1)
ans = inf
for i, v in enumerate(arr, 1):
s += v
f[i] = f[i - 1]
if s - target in d:
j = d[s - target]
f[i] = min(f[i], i - j)
ans = min(ans, f[j] + i - j)
d[s] = i
return -1 if ans > n else ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the array auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
LeetCode 792Number of Matching SubsequencesMediumLeetCode 1027Longest Arithmetic SubsequenceMediumLeetCode 1658Minimum Operations to Reduce X to ZeroMediumLeetCode 2008Maximum Earnings From TaxiMediumLeetCode 2009Minimum Number of Operations to Make Array ContinuousHardLeetCode 2501Longest Square Streak in an ArrayMedium
Frequently asked questions
- How hard is LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum?
- LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum?
- The Python solution on this page uses O(n), where n is the length of the array auxiliary space.
- What topics does LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum cover?
- LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum is tagged Array, Hash Table, Binary Search, Dynamic Programming and Sliding Window on LeetCode.