Find Two Non-overlapping Sub-arrays Each With Target Sum — LeetCode 1477 Python Solution

MediumArrayHash TableBinary SearchDynamic ProgrammingSliding Window
Problem
#1477
Reading time
3 min

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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview