876268. Subarray with Given Sum
Easy
Subarray with Given Sum
Summary
Given an array of integers and a target sum, find all subarrays that have a sum equal to the given target sum. This problem can be approached using the sliding window technique.
Detailed Explanation
The main idea is to maintain two pointers, start and end, which represent the start and end indices of the current window. Initialize the start pointer at the beginning of the array and set the sum variable to zero.
- Iterate through the array using the
endpointer. - For each element, add its value to the
sum. - If the
sumequals the target sum, then we have found a subarray that sums up to the target sum. - To find all such subarrays, maintain a set of unique subarrays and update it with each new subarray found.
- Continue the process until the
endpointer reaches the end of the array.
The time complexity for this algorithm is O(n), where n is the number of elements in the array. The space complexity is also O(n) for storing all the unique subarrays.
Here is an ASCII art diagram representing the sliding window:
0 1 2 3 4 5
|---|---|
start end
Optimized Solutions
Java
import java.util.*;
public class SubarrayWithGivenSum {
public static List<List<Integer>> subarrays(int[] arr, int target) {
List<List<Integer>> result = new ArrayList<>();
Map<Integer, Integer> sumIndexMap = new HashMap<>();
int start = 0;
int currentSum = 0;
for (int end = 0; end < arr.length; end++) {
currentSum += arr[end];
if (currentSum == target) {
List<Integer> subarray = new ArrayList<>();
for (int i = start; i <= end; i++) {
subarray.add(arr[i]);
}
result.add(subarray);
} else if (sumIndexMap.containsKey(currentSum - target)) {
start = sumIndexMap.get(currentSum - target) + 1;
currentSum -= arr[start];
}
sumIndexMap.put(currentSum, end);
}
return result;
}
}