Subarray Sums Divisible by K

Given an integer array nums and an integer k, return the number of non-empty subarrays whose sum is divisible by k. A subarray is a contiguous part of the array.

30:00

Subarray Sums Divisible by K
medium
Free written solution
Topics
Companies

Given an integer array nums and an integer k, return the number of non-empty subarrays whose sum is divisible by k. A subarray is a contiguous part of the array.

Example 1:
Input: {"nums":[4,5,0,-2,-3,1],"k":5}
Output: 7
Constraints:
  • 1≤nums.length≤3×1041 \leq \text{nums.length} \leq 3 \times 10^4

  • −104≤nums[i]≤104-10^4 \leq \text{nums}[i] \leq 10^4

  • 2≤k≤1042 \leq k \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[4,5,0,-2,-3,1],"k":5}

The empty prefix has sum 0, so bucket 0 starts with one entry. Two prefixes with the same remainder mod 5 enclose a subarray whose sum is divisible by 5.

nums, with prefix mod 5 after each element

start

0

0

4
·

1

5
·

2

0
·

3

-2
·

4

-3
·

5

1
·

bottom row: prefix sum mod 5 after that element (first box is the empty prefix)

remainder buckets: count[r] = prefixes seen with remainder r

r = 0

P0

1

r = 1

0

r = 2

0

r = 3

0

r = 4

0

prefix mod 5 = 0
result = 0
Variables
VariableValue
k5
prefix0
result0
DepthFunction Call
Stack empty
0/19