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

https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/

class Solution:
    def minSumOfLengths(self, arr: List[int], target: int) -> int:
        if len(arr) == 0:
            return -1
        n = len(arr)
        presum = [0] * n
        presum[0] = arr[0]
        for i in range(1,n):
            presum[i] = presum[i-1] + arr[i]
        presumIndex = dict()
        presumIndex[0] = -1
        shortestTill = [float("inf")] * len(arr)
        res = float("inf")
        shortest = float("inf")
        for i,val in enumerate(presum):
            if val - target in presumIndex:
                end = presumIndex[val-target]
                if end != -1:
                    res = min(res,i - end + shortestTill[end])
                shortest = min(shortest, i - end)
            shortestTill[i] = shortest
            presumIndex[val] = i
        return res if res != float("inf") else -1
            
        

Last updated

Was this helpful?