KatInterview

Detect a Run of Two or More Elements Summing to a Multiple of k

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingprefix sumhash mapremainders

Last updated

Tests prefix-sum reasoning with hashing: detecting a contiguous run of length at least two whose sum is divisible by k, including the k = 0 special case.

Problem

You are given an integer array nums and an integer k. Decide whether there is a contiguous block of elements whose length is at least 2 and whose sum is a multiple of k.

Return True if such a block exists, otherwise return False.

Definitions:

  • A block is a run of consecutive positions nums[l..r] with r - l + 1 >= 2.
  • A sum is a multiple of k when it equals k * m for some integer m. This is the same as being a multiple of |k|.
  • If k = 0, the requirement changes: the block's sum must be exactly 0.

Explain your approach, and state the time and space complexity of your solution.

Constraints

  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= k <= 10^9
  • Blocks must have length at least 2. A single element never counts, even if it is itself a multiple of k.
  • Return a Python bool.

Examples

Example 1

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

Output: True

Example 2

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

Output: True

Example 3

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

Output: False

Hints

Hint 1

Turn the block sum into a difference of two prefix sums. If P[i] is the sum of the first i+1 elements, the block from index j+1 to i has sum P[i] - P[j], which is a multiple of k exactly when P[i] and P[j] share a remainder mod |k|.

Hint 2

Store only the earliest index for each remainder. For the length-at-least-2 rule, the earliest index gives the longest possible block, so it is the only one worth remembering. Seed the map with remainder 0 at index -1 so that blocks starting at index 0 are counted.

Hint 3

When k = 0, skip the remainder step and use the raw prefix sum as the key. Also check whether abs(k) works as the divisor for negative k, and how your language's % handles negative prefix sums.