AlgoInsight

DSA problem

Subarray Sums Divisible by K

MediumPrefix SumPattern: Prefix Sum + Hash Maptop300AmazonGoogleMicrosoftFacebook

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.

The brute-force approach of checking every subarray runs in O(n^2) time. The key observation is that a subarray sum from index i+1 to j is divisible by k if and only if the prefix sums at i and j have the same remainder when divided by k. By tracking how many times each remainder has been seen, we can count valid subarrays in a single pass. Care must be taken with negative numbers: in many languages the modulo of a negative value can be negative, so normalize the remainder into the range [0, k).

Examples

Example 1
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], and [-2,-3].
Example 2
Input: nums = [5], k = 9
Output: 0
Explanation: The only subarray is [5], whose sum 5 is not divisible by 9.
Example 3
Input: nums = [-1,2,9], k = 2
Output: 2
Explanation: The subarrays [-1,2,9] (sum 10) and [2] (sum 2) are both divisible by 2.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

prefix-sumhash-maparraymath

Browse all DSA problems