881453. Subarray sum
Medium
Subarray Sum
Summary
Given an array of integers, find all subarrays whose sum is equal to a given target value. This problem involves understanding the concept of subarrays and how to efficiently calculate their sums.
Detailed Explanation
To solve this problem, we will use a simple and intuitive approach. We iterate through the array and for each element, we calculate the sum of all subarrays ending at that element. If the calculated sum is equal to the target value, we add it to our result list.
Here's a step-by-step breakdown of the solution:
- Initialize an empty list
resultto store the subarrays with the desired sum. - Iterate through the array using two pointers
startandend. - Calculate the sum of all elements between
startandend(inclusive) and store it in a variablecurrent_sum. - If
current_sumis equal to the target value, add the subarray fromstarttoendto theresultlist. - Move the
startpointer one step forward and updatecurrent_sumby subtracting the element at the previousstartposition and adding the current element at theendposition. - Repeat steps 3-5 until
endreaches the end of the array.
Time complexity: O(n), where n is the length of the array, since we only need to iterate through the array once. Space complexity: O(1), as we only use a constant amount of space to store the result list and other variables.
Optimized Solutions
Java
import java.util.ArrayList;
import java.util.List;
public class SubarraySum {
public static List<List<Integer>> subarraySum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
int start = 0, end = 0, current_sum = 0;
while (end < nums.length) {
current_sum += nums[end];
if (current_sum == target) {
List<Integer> subarray = new ArrayList<>();
for (int i = start; i <= end; i++) {
subarray.add(nums[i]);
}
result.add(subarray);
}
while (start <= end && current_sum > target) {
current_sum -= nums[start];
start++;
}
end++;
}
return result;
}
}