<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of non-empty <strong>subarrays</strong> that have a sum divisible by </em><code>k</code>.</p>

<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [4,5,0,-2,-3,1], k = 5
<strong>Output:</strong> 7
<strong>Explanation:</strong> 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]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [5], k = 9
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
	<li><code>2 &lt;= k &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution {
public:
    int subarraysDivByK(vector<int>& nums, int k) {
        //return -2 % 6;
        int n = nums.size();
        vector<int> p(n + 1);
        p[0] = 0;
        for(int i = 0;i < n;i++) {
            p[i + 1] = nums[i] + p[i];
        }
        // Sub Array Sum == p[i] - p[j - 1] == n * k
        // Remainder of p[i] == Remainder of p[j - 1] from k
        // Remainders can be 0, 1, 2, ... k - 1

        // 1 <= j <= i <= n
        vector<int> ModGroups(k, 0);
        // Selecting 2 from them would be nc2
        int ans = 0;

        for(int i = 0;i <= n;i++) {
            int mod1 = (p[i] % k);
            // Avoid negative mod
            int mod2 = (mod1 + k*(abs(mod1)+1)) % k;
            ModGroups[mod2]++;
        }

        for(int t = 0;t < k;t++) {
            int n = ModGroups[t];
            int pairs = (n * (n - 1)) / 2;
            ans += pairs;
        }

        return ans;
    }
};
33800