#523

Continuous Subarray Sum

Medium Prefix remainders + index

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Decide whether there is a subarray of length at least 2 whose sum is a multiple of k.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: is there a piece of length ≥ 2 whose sum is a multiple of k?

Why this works: same remainder twice means the part between them is a multiple of k. Store the first index of each remainder so the gap check (≥ 2) is fair.

Example: [23, 2, 4, 6, 7], k = 6

remainders: 5, 1, 5 …remainder 5 at index 0 and index 2 → gap 2 → [2, 4] sums to 6 ✓

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Storing the latest index; then a length-1 subarray can block a valid longer one.