974. Subarray Sums Divisible by K
Problem description:
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.
Example 1:
1 | Input: nums = [4,5,0,-2,-3,1], k = 5 |
Example 2:
1 | Input: nums = [5], k = 9 |
Constraints:
1 <= nums.length <= 3 * 104
104 <= nums[i] <= 104
2 <= k <= 104
Solution:
1 | Input: A = [4,5,0,-2,-3,1], K = 5 |
For negative modulo
1 | It's calculated exactly like the mod of a positive number. |
1 | class Solution: |
We actually only need array with size k
1 | class Solution: |
time complexity: $O(n)$
space complexity: $O(k)$
reference:
related problem: