MrainW's Home

All things come to those who wait!

0%

LeetCode 974. Subarray Sums Divisible by K

Question

Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.

A subarray is a contiguous part of an array.

https://leetcode.com/problems/subarray-sums-divisible-by-k/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int subarraysDivByK(int[] A, int K) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
int count = 0, sum = 0;
for(int a : A) {
sum = (sum + a) % K;
if(sum < 0) sum += K; // Because -1 % 5 = -1, but we need the positive mod 4
count += map.getOrDefault(sum, 0);
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return count;
}
}

Complexity:

Time complexity: O( n)

Space complexity: O(n)

Welcome to my other publishing channels