LeetCode 523 Continuous Subarray Sum - Solution

The core idea

Track the running prefix sum modulo k. If two positions have the same remainder, the subarray between them sums to a multiple of k.

Why? If prefix[i] % k == prefix[j] % k, then prefix[j] - prefix[i] is divisible by k. That difference is exactly the sum of the subarray from i+1 to j.

Use a hash map to store the first index where each remainder appeared. When you see a remainder again, check if the gap is at least 2 (subarray length requirement).

Initialize the map with {0: -1} to handle subarrays starting from index 0. If the prefix sum itself is divisible by k at index 1 or later, that's a valid subarray.