701292. Subarray range with given sum
Medium
Subarray Range with Given Sum
Summary
Find all subarrays in a given array that sum up to a certain value. This problem is an extension of the "Minimum Size Subarray Sum" problem, where we need to find all subarrays instead of just one.
Detailed Explanation
To solve this problem, we can use a hash map (or a dictionary) to store the cumulative sum of elements and their indices. We iterate over the array and for each element, calculate its cumulative sum up to that point. If the cumulative sum minus the given sum is present in our hash map, it means we have found a subarray with the given sum.
Here's a step-by-step breakdown:
- Initialize an empty hash map
cumulativeSumToIndex. - Iterate over the array and for each element:
- Calculate its cumulative sum up to that point.
- If the cumulative sum minus the given sum is present in our hash map, it means we have found a subarray with the given sum.
- Add this subarray's start index to our result list.
- Continue iterating until the end of the array.
Optimized Solutions
Java
import java.util.HashMap;
import java.util.Map;
public class SubarrayRange {
public static int[] findSubarrays(int[] arr, int sum) {
Map<Integer, Integer> cumulativeSumToIndex = new HashMap<>();
int cumulativeSum = 0;
List<Integer> subarrayStartIndices = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
cumulativeSum += arr[i];
if (cumulativeSum - sum >= 0 && cumulativeSumToIndex.containsKey(cumulativeSum - sum)) {
subarrayStartIndices.add(cumulativeSumToIndex.get(cumulativeSum - sum));
}
cumulativeSumToIndex.put(cumulativeSum, i);
}
return subarrayStartIndices.stream().mapToInt(Integer::intValue).toArray();
}
}