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

grid47
grid47
Exploring patterns and algorithms
Jun 12, 2024 6 min read

You are given an array of integers arr and an integer target. You need to find two non-overlapping sub-arrays of arr each with a sum equal target. The goal is to minimize the sum of their lengths, and if no such sub-arrays exist, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array arr and an integer target.
Example: [1, 1, 1, 2, 3], 2
Constraints:
• 1 <= arr.length <= 10^5
• 1 <= arr[i] <= 1000
• 1 <= target <= 10^8
Output: The output should return the minimum sum of the lengths of the two sub-arrays, or -1 if no such sub-arrays exist.
Example: 2
Constraints:
• If no two sub-arrays with sum equal to target exist, return -1.
Goal: The goal is to efficiently find two non-overlapping sub-arrays that sum to the target and minimize the sum of their lengths.
Steps:
• Use a sliding window approach to find all sub-arrays that sum to the target.
• Store the lengths of valid sub-arrays and ensure they do not overlap.
• Track the minimum sum of lengths for valid sub-arrays.
Goal: Ensure the input size does not exceed the constraints and that the array elements and target are within the given limits.
Steps:
• 1 <= arr.length <= 10^5
• 1 <= arr[i] <= 1000
• 1 <= target <= 10^8
Assumptions:
• The array will contain at least one sub-array summing to the target.
Input: [1, 1, 1, 2, 3], 2
Explanation: Here, two sub-arrays sum to 2: [1, 1] and [2], and the sum of their lengths is 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus