Problem · Array

Count Subarrays With Sum Divisible by K

Learn this problem
MediumInMobi logoInMobiNEW GRADOA

Problem statement

Given an integer array arr and a positive integer k, return the number of non-empty contiguous subarrays whose element sum is divisible by k.

A subarray is a contiguous sequence of elements from arr. A sum s is divisible by k when s % k = 0.

Function

countDivisibleSubarrays(arr: int[], k: int) → long

Examples

Example 1

arr = [2,3,1]k = 2return = 3

The qualifying subarrays are [2], [3,1], and [2,3,1], with sums 2, 4, and 6.

Example 2

arr = [1,2,3,4]k = 1return = 10

Every integer sum is divisible by 1, so all 4 × 5 / 2 = 10 non-empty subarrays qualify.

Example 3

arr = [-1,2,9]k = 2return = 2

The qualifying subarrays are [2], whose sum is 2, and [-1,2,9], whose sum is 10.

Constraints

  • 1 ≤ arr.length ≤ 10^4
  • 1 ≤ k ≤ 10^4
  • -10^9 ≤ arr[i] ≤ 10^9

More InMobi problems

drafts saved locally
public long countDivisibleSubarrays(int[] arr, int k) {
  // write your code here
}
arr[2,3,1]
k2
expected3
checking account