702918. Subarray Sum Divisible By K
Medium
Subarray Sum Divisible By K
Summary
Given an array nums and an integer k, find all subarrays that sum up to a value divisible by k. This problem involves arrays, data structures, and prefix sums.
Detailed Explanation
The key idea is to use prefix sums to efficiently calculate the sum of any subarray. We can iterate through the array and for each element, calculate the sum of the subarray ending at that element using the previously calculated prefix sum. Then, we check if this sum is divisible by k and if it is, add the subarray to our result set.
Here's a step-by-step breakdown:
- Initialize an empty list
resultto store the subarrays. - Calculate the total sum of the array using a single pass through the array.
- Iterate through the array again:
- For each element
num, calculate the prefix sumpsup to that point. - Check if
ps % k == 0. If it is, add all subarrays ending atnumtoresult.
- For each element
- Return
result.
Time complexity: O(n), where n is the length of the array. We iterate through the array twice.
Space complexity: O(n), for storing the prefix sums and result set.
Optimized Solutions
Java
import java.util.ArrayList;
import java.util.List;
public class SubarraySumDivisibleByK {
public List<List<Integer>> subarraysWithSumDivisibleByK(int[] nums, int k) {
List<List<Integer>> result = new ArrayList<>();
long totalSum = 0;
for (int num : nums) {
totalSum += num;
}
for (int i = 0; i < nums.length; i++) {
long ps = 0;
for (int j = i; j >= 0; j--) {
ps += nums[j];
if (ps % k == 0) {
List<Integer> subarray = new ArrayList<>();
for (int m = j; m <= i; m++) {
subarray.add(nums[m]);
}
result.add(subarray);
}
}
}
return result;
}
}