Subarray Sums Divisible by K — LeetCode 974 Python Solution
MediumArrayHash TablePrefix Sum
- Problem
- #974
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- Input
- nums = [4,5,0,-2,-3,1], k = 5
- Output
- 7
- Explanation
- There are 7 subarrays with a sum divisible by k = 5:
Python solution
Python
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
cnt = Counter({0: 1})
ans = s = 0
for x in nums:
s = (s + x) % k
ans += cnt[s]
cnt[s] += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 974. Subarray Sums Divisible by K is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 974. Subarray Sums Divisible by K?
- LeetCode 974. Subarray Sums Divisible by K is rated Medium on LeetCode.
- What is the time complexity of LeetCode 974. Subarray Sums Divisible by K?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 974. Subarray Sums Divisible by K?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 974. Subarray Sums Divisible by K cover?
- LeetCode 974. Subarray Sums Divisible by K is tagged Array, Hash Table and Prefix Sum on LeetCode.