Subarray Sums Divisible by K

MediumArrays & Hashingprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums (values may be negative) and an integer k, count the non-empty contiguous subarrays whose sum is divisible by k. Two subarrays are different if they start or end at different indices, even if their contents are equal. Return the count as an integer. An O(n + k) solution is expected.

Examples

Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
The qualifying subarrays are [5], [5,0], [5,0,-2,-3], [0], [0,-2,-3], [-2,-3], and [4,5,0,-2,-3,1].
Input: nums = [5], k = 9
Output: 0
5 is not divisible by 9.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -10^4 <= nums[i] <= 10^4
  • 2 <= k <= 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems