Continuous Subarray Sum

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 a non-negative integer array nums and a positive integer k, decide whether nums contains a contiguous subarray of **length at least 2** whose sum is a multiple of k. A sum s counts as a multiple of k when s % k == 0; in particular 0 is a multiple of every k. Return true if such a subarray exists and false otherwise. Target O(n) time.

Examples

Input: nums = [23,2,4,6,7], k = 6
Output: true
[2,4] has length 2 and sums to 6.
Input: nums = [23,2,6,4,7], k = 13
Output: false
No subarray of length 2 or more sums to a multiple of 13.
Input: nums = [5,0,0,0], k = 3
Output: true
[0,0] sums to 0, which is a multiple of 3.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^9
  • 0 <= sum(nums) <= 2^31 - 1
  • 1 <= k <= 2^31 - 1

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