121. Sums Aligned with a Divisor
Medium
Given a sequence of values, a team wants to find contiguous segments whose sum can be divided by k with no remainder. Since values may be negative, treat a sum as divisible when its mathematical remainder is zero.
Return the number of contiguous subarrays of nums whose sum is divisible by k.
Example 1
Input: nums = [4, 5, 0, -2, -3, 1], k = 5
Output: 7
Explanation: There are seven contiguous segments whose sums are divisible by 5.
Example 2
Input: nums = [-2, 1, 1, -2], k = 3
Output: 2
Explanation: The two zero-sum segments are divisible by 3.
Example 3
Input: nums = [0, 0], k = 7
Output: 3
Explanation: The two single-element subarrays and the full subarray have sums divisible by 7.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- 1 <= k <= 10^9
Prefix sumsHash map
Saved in this browser
Caso 1
nums =
[4,5,0,-2,-3,1]
k =
5
Expected =
7
Caso 2
nums =
[-2,1,1,-2]
k =
3
Expected =
2
Caso 3
nums =
[0,0]
k =
7
Expected =
3
Run checks these 3 cases. Submit runs all 12, including hidden ones.