Problem Description
Given a 0-indexed integer array nums and an integer d, count the number of triplets (i, j, k) with i < j < k such that the sum of the corresponding elements is divisible by d.
Key Insights
- Pre-compute each number’s remainder modulo d to simplify the sum computations.
- Use a double loop to fix the first two indices (i, j) and then determine the necessary remainder for the third index k.
- Build a suffix frequency structure for remainders so that for each index j, you can quickly obtain the count of valid k-values (k > j) having the required remainder.
- Although a naive brute force triple loop would be O(n^3), using the suffix count reduces it to O(n^2), which is acceptable for n up to 1000.
Space and Time Complexity
Time Complexity: O(n^2)
Space Complexity: O(n) (for storing suffix remainder counts; note that the number of distinct remainders encountered is at most n)
Solution
The solution starts by computing the modulo d value for each element in nums. It then precomputes a suffix frequency array such that for every index, you have a dictionary counting the occurrence of each remainder from that index to the end. For every pair (i, j) with i < j, we calculate the required remainder for k so that (nums[i] + nums[j] + nums[k]) % d == 0 can hold. Using the suffix frequency array, we quickly find how many valid indices k exist for each chosen pair. This efficient counting avoids the need for a third nested loop and leverages hash tables to compute the required frequency counts in O(1) time per lookup.