Leetcode 2176. Count Equal and Divisible Pairs in an Array
You are given a 0-indexed integer array nums of length n and an integer k. Find the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.
nums and k: What are the constraints for the values in nums and the value of k?
nums can have positive or negative integers, including zero?k is a positive integer?nums: What is the maximum length of the array nums?
nums are distinct?(i, j) where i < j.nums[i] == nums[j] and if (i * j) % k == 0.i < j, for a fixed j, we can try to use a hash map to store previously seen values and their corresponding indices, allowing for quick lookups and reducing the number of comparisons.Let’s start with the brute force approach for simplicity, and then consider any necessary optimizations based on the performance.
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int countPairs(vector<int>& nums, int k) {
int n = nums.size();
int count = 0;
// Brute force approach to check all pairs (i, j) where i < j.
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] == nums[j] && (i * j) % k == 0) {
++count;
}
}
}
return count;
}
};
countPairs initializes n to the size of nums and count to 0.i moves from 0 to n-1 and j moves from i+1 to n.(i, j), it checks if nums[i] == nums[j] and if (i * j) % k == 0.count.(i, j) is considered.To optimize, we can use additional data structures such as hash maps to store indices and precompute product divisibility conditions. This would reduce the number of checks per comparison:
Would you like to see this optimized version as well?
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?