Link to the problem

The problem is here: https://leetcode-cn.com/problems/continuous-subarray-sum/

Problem description

Given an array nums of non-negative numbers and a number k, return true if there exists a subarray of nums (with at least 2 elements) that sums up to a multiple of k.

Idea

It is a very typical problem to use the prefix-sum algorithm. We define lc-523 Continuous Subarray Sum - 图1, and for simplicity, lc-523 Continuous Subarray Sum - 图2. The problem is actually to find a tuple lc-523 Continuous Subarray Sum - 图3 s.t. lc-523 Continuous Subarray Sum - 图4.

Here we need to use a math trick: lc-523 Continuous Subarray Sum - 图5.

Instead of memorizing the prefix-summations, we need to store the reminders. And for each , check whether there exists a , s.t. .

Implementation

My implementation is this:

  1. bool checkSubarraySum(vector<int>& nums, int k) {
  2. unordered_map<int, int> mp;
  3. mp[0] = -1;
  4. int sum = 0;
  5. for (int i = 0; i < nums.size(); i++) {
  6. sum += nums[i];
  7. int rem = sum % k;
  8. auto it = mp.find(rem);
  9. if (it == mp.end()) {
  10. mp[rem] = i;
  11. } else if (it->second <= i - 2) {
  12. return true;
  13. }
  14. }
  15. return false;
  16. }