Skip to content

Commit 0b93a71

Browse files
committed
O(n) time and O(n) space using Prefix Sum and Hashtable.
1 parent 6995fb7 commit 0b93a71

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.
3+
4+
5+
6+
Example 1:
7+
8+
Input: A = [4,5,0,-2,-3,1], K = 5
9+
Output: 7
10+
Explanation: There are 7 subarrays with a sum divisible by K = 5:
11+
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
12+
13+
14+
Note:
15+
16+
1 <= A.length <= 30000
17+
-10000 <= A[i] <= 10000
18+
2 <= K <= 10000
19+
"""
20+
class Solution:
21+
def subarraysDivByK(self, A: List[int], K: int) -> int:
22+
hmap,total,result = {},0,0
23+
for num in A:
24+
hmap[total] = hmap.get(total,0) + 1
25+
total += num
26+
total %= K
27+
if hmap.get(total):
28+
result += hmap[total]
29+
return result

0 commit comments

Comments
 (0)