Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

Count subarrays with a sum divisible by k

Medium · Target 20 minutes · Arrays and hashing· Type asked at

Count subarrays with a sum divisible by k

You're given an integer array nums that may hold negative numbers and a positive integer k. I'd like you to count how many contiguous subarrays have a sum that divides exactly by k. Ranges are counted by where they sit in the array, so two ranges holding the same values at different positions both count towards the total.

Examples

InputOutputWhy
nums = [4, 5, 0, -2, -3, 1], k = 57They're [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] and the whole array.
nums = [5], k = 90There's only the one range here and 5 doesn't divide by 9.
nums = [0, 0, 0], k = 36Every one of the six ranges adds up to 0, and 0 divides by anything.

Constraints

  • 1 ≤ n ≤ 3 × 10⁴
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • 1 ≤ k ≤ 10⁴

Hints

Hint 1

I'd start from prefix sums again because a range is still the difference P[j] − P[i] of two prefixes.

Hint 2

That difference divides by k exactly when P[i] and P[j] leave the same remainder after dividing by k, so the remainder is what you should be looking up.

Hint 3

Keep a count of how many prefixes you've seen with each remainder and start it at {0: 1}. Then watch what your language does with the remainder of a negative number.

Where people lose marks

  • The mistake I see most often in interviews is taking the remainder with a plain % in a language where it can come out negative. However tidy the rest of the solution is, that quietly splits one remainder class into two separate keys, and the answer comes out too small with no error to warn you.
  • Forgetting to start the count for remainder 0 at 1 rather than 0. Everything still compiles and runs happily, and every range that begins at the very first element of the array disappears from the total.
  • Recording the current prefix in the counts before you've read them. Each prefix then matches itself, so the empty range gets counted once at every step of the sweep. Overall, I'd recommend reading first and recording second, in this problem and in the earlier counting one.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.