Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find two non-overlapping sub-arrays each with target sum using Python
Given an array and a target sum, we need to find two non-overlapping sub-arrays where each has a sum equal to the target. If multiple solutions exist, we return the one with the minimum combined length of both sub-arrays.
So, if the input is like arr = [5,2,6,3,2,5] and target = 5, then the output will be 2. There are three subarrays with sum 5: [5], [3,2], and [5]. We can choose two sub-arrays of length 1 each, giving us a minimum combined length of 2.
Algorithm Approach
We use a prefix sum approach combined with dynamic programming:
ans:= stores the minimum combined length found so farbest:= array storing the shortest subarray length ending at each positionprefix:= running sum of elementslatest:= map storing the most recent index for each prefix sum
For each position, we check if there's a previous prefix sum that would create a subarray with target sum. We then try to combine it with the best subarray found before that position.
Implementation
def solve(arr, target):
ans = float('inf')
best = [float('inf')] * len(arr)
prefix = 0
latest = {0: -1}
for i, x in enumerate(arr):
prefix += x
# Check if we can form a subarray with target sum ending at position i
if prefix - target in latest:
ii = latest[prefix - target]
if ii >= 0:
# Try to combine current subarray with best subarray before position ii
ans = min(ans, i - ii + best[ii])
# Update best[i] with current subarray length
best[i] = i - ii
# Update best[i] with minimum of previous best and current best
if i > 0:
best[i] = min(best[i-1], best[i])
# Store current prefix sum and its index
latest[prefix] = i
return ans if ans != float('inf') else -1
# Test the function
arr = [5, 2, 6, 3, 2, 5]
target = 5
result = solve(arr, target)
print(f"Minimum combined length: {result}")
Minimum combined length: 2
How It Works
The algorithm works by:
Tracking prefix sums: We maintain a running sum and check if
prefix - targetexists in our mapFinding subarrays: When
prefix - targetis found, we've identified a subarray with sum equal to targetDynamic programming: We keep track of the best (shortest) subarray length found up to each position
Combining results: For each valid subarray, we try to combine it with the best subarray found before it
Example Walkthrough
For arr = [5,2,6,3,2,5] and target = 5:
Position 0:
[5]has sum 5 (length 1)Position 3-4:
[3,2]has sum 5 (length 2)Position 5:
[5]has sum 5 (length 1)
We can choose the first [5] and last [5], giving us a combined length of 2.
Conclusion
This solution efficiently finds two non-overlapping subarrays with target sum using prefix sums and dynamic programming. The time complexity is O(n) and space complexity is O(n), making it optimal for this problem.
