KatInterview

Contiguous Subarray with Sum Divisible by K

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingprefix-sumhash-mapmodular-arithmetic

Last updated

Tests whether a candidate can apply prefix-sum modular arithmetic to detect a length-≥2 subarray whose sum divides evenly by k in linear time.

Contiguous Subarray with Sum Divisible by K

You are given an array of non-negative integers nums and a positive integer k.

Return True if there is a contiguous subarray of length at least 2 whose elements sum to a multiple of k. Otherwise return False.

A sum is a multiple of k when the remainder after dividing by k equals zero.

Constraints

  • 1 <= len(nums) <= 100 000
  • 0 <= nums[i] <= 1 000 000 000
  • 1 <= k <= 1 000 000 000
  • Aim for an O(n) solution.

Examples

Example 1

Input: check_subarray_sum([23, 2, 4, 6, 7], 6)

Output: True

Example 2

Input: check_subarray_sum([23, 2, 6, 4, 7], 6)

Output: True

Example 3

Input: check_subarray_sum([23, 2, 6, 4, 7], 13)

Output: False

Hints

Hint 1

Define the prefix sum P[i] as the sum of the first i elements. The sum of subarray nums[a..b] equals P[b+1] − P[a]. What condition on P[b+1] and P[a] guarantees that sum is divisible by k?

Hint 2

Two prefix sums that share the same remainder mod k correspond to a subarray whose sum is divisible by k. Use a dictionary to record the earliest index where each remainder was seen, then check whether the gap between that index and the current index is at least 2.

Hint 3

Seed your remainder map with {0: −1} before you start. This handles subarrays that begin at index 0. Never overwrite an existing entry — you always want the earliest occurrence so the gap can only grow, never shrink.