← All solutions
September 17Medium

Find two non overlapping sub arrays each with target sum

  • Array
  • Hash Table
  • Binary Search
  • Dynamic Programming
  • Sliding Window

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. 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.

Solution

class Solution:
    def minSumOfLengths(self, arr: list[int], target: int) -> int:
        n = len(arr)
        suffix = [float("inf")] * (n + 1)
        end = n - 1
        curr_sum = 0
        for start in range(n-1, -1, -1):
            curr_sum += arr[start]
            while curr_sum > target:
                curr_sum -= arr[end]
                end -= 1
            if curr_sum == target:
                length = end - start + 1
                suffix[start] = min(length, suffix[start + 1])
            else:
                suffix[start] = suffix[start + 1] 

        curr_sum = 0
        start = 0
        res = float("inf")
        for j in range(n):
            curr_sum += arr[j]
            while curr_sum > target:
                curr_sum -= arr[start]
                start += 1
            if curr_sum == target:
                res = min(res, j - start + 1 + suffix[j + 1])

        return res if res != float("inf") else -1