Subarray Sums Divisible by K - Problem
You're given an integer array nums and an integer k. Your task is to find the number of contiguous subarrays whose sum is divisible by k.

A subarray is a contiguous part of an array, meaning elements must be adjacent to each other. For example, in array [4, 5, 0, -2, -3, 1] with k = 5, subarrays like [5], [5, 0], and [0, -2, -3] have sums divisible by 5.

Goal: Count all such subarrays efficiently without generating them explicitly.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [4,5,0,-2,-3,1], k = 5
โ€บ Output: 7
๐Ÿ’ก Note: The subarrays with sums divisible by 5 are: [5], [5,0], [5,0,-2,-3], [0], [0,-2,-3], [-2,-3], and [4,5,0,-2,-3,1] (whole array). Total count = 7.
example_2.py โ€” Single Element
$ Input: nums = [5], k = 9
โ€บ Output: 0
๐Ÿ’ก Note: The only subarray is [5] with sum 5, which is not divisible by 9. Therefore, count = 0.
example_3.py โ€” All Elements Divisible
$ Input: nums = [3,6,9], k = 3
โ€บ Output: 6
๐Ÿ’ก Note: All possible subarrays have sums divisible by 3: [3], [6], [9], [3,6], [6,9], [3,6,9]. Total count = 6.

Constraints

  • 1 โ‰ค nums.length โ‰ค 3 ร— 104
  • -104 โ‰ค nums[i] โ‰ค 104
  • 2 โ‰ค k โ‰ค 104
  • Note: Array can contain negative numbers

Visualization

Tap to expand
Remainder Clock (k=5)01234When prefix sums land on same position โ†’ valid subarray!
Understanding the Visualization
1
Initialize
Start with remainder 0 seen once (empty prefix)
2
Process Elements
For each element, update prefix sum and find remainder
3
Count & Update
Add current remainder frequency to result, then increment frequency
Key Takeaway
๐ŸŽฏ Key Insight: Modular arithmetic transforms the subarray sum problem into a frequency counting problem!
Asked in
Amazon 45 Google 38 Meta 32 Microsoft 28 Apple 22
38.2K Views
High Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen