Skip to content

Latest commit

 

History

History
60 lines (47 loc) · 1.82 KB

README.md

File metadata and controls

60 lines (47 loc) · 1.82 KB

Given an array nums of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by k.

 

Example 1:

Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by k = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]

 

Note:

  1. 1 <= nums.length <= 30000
  2. -10000 <= nums[i] <= 10000
  3. 2 <= k <= 10000

Companies:
Twilio, Facebook

Related Topics:
Array, Hash Table

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/subarray-sums-divisible-by-k/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(K)
class Solution {
public:
    int subarraysDivByK(vector<int>& A, int k) {
        unordered_map<int, int> m{{0,1}};
        int sum = 0, ans = 0;
        for (int n : A) {
            sum += n;
            if (sum >= 0) sum %= k;
            else sum = (k - (-sum % k)) % k;
            ans += m[sum];
            m[sum]++;
        }
        return ans;
    }
};