Problem Description
Given an array of integers and a target sum, find two non-overlapping sub-arrays each whose sum equals the target. The goal is to minimize the sum of the lengths of these two sub-arrays. If no such pair exists, return -1.
Key Insights
- Use a sliding window because the array consists of positive integers.
- Maintain a dynamic programming (dp) array to record the minimum length of any valid sub-array ending at or before each index.
- As a valid sub-array is found using the sliding window, check the dp array for a candidate sub-array in the left portion that does not overlap with the current one.
- Update the result minimizing the combined lengths of the two sub-arrays.
Space and Time Complexity
Time Complexity: O(n) - Single (or two) linear pass(es) through the array. Space Complexity: O(n) - For maintaining the dp array that stores minimal sub-array lengths.
Solution
The solution is based on a sliding window approach to identify sub-arrays that sum to the target. As we iterate with the window, we keep the best candidate (smallest length sub-array) up to the current index in a dp array. When we find a valid sub-array with sum equal to the target, we then check if a previous non-overlapping valid sub-array exists by looking at dp[left-1]. If found, we update the minimum total length. This technique efficiently ensures that the sub-arrays do not overlap and that their total length is minimized.