> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Subarray Sums Divisible by K Python Solution

> Tested Python solution for LeetCode 974 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 974, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [Prefix Sum](/catalog/topics/prefix-sum). [View on LeetCode](https://leetcode.com/problems/subarray-sums-divisible-by-k/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 974   # by problem number
lcpy gen -s subarray_sums_divisible_by_k   # by problem name
```

## 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.

### Examples

```
Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by k = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
```

```
Input: nums = [5], k = 9
Output: 0
```

### Constraints

* `1 <= nums.length <= 3 * 10^4`
* `-10^4 <= nums[i] <= 10^4`
* `2 <= k <= 10^4`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/subarray_sums_divisible_by_k/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/subarray_sums_divisible_by_k/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(k)
    def subarrays_div_by_k(self, nums: list[int], k: int) -> int:
        mod_count: dict[int, int] = {0: 1}
        prefix_mod = 0
        count = 0
        for num in nums:
            prefix_mod = (prefix_mod + num) % k
            count += mod_count.get(prefix_mod, 0)
            mod_count[prefix_mod] = mod_count.get(prefix_mod, 0) + 1
        return count
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(k) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.