2176. Count Equal and Divisible Pairs in an Array
Description
Given a 0-indexed integer array nums
of length n
and an integer k
, return the number of pairs (i, j)
where 0 <= i < j < n
, such that nums[i] == nums[j]
and (i * j)
is divisible by k
.
Example 1:
Input: nums = [3,1,2,2,2,1,3], k = 2 Output: 4 Explanation: There are 4 pairs that meet all the requirements: - nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2. - nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2. - nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2. - nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.
Example 2:
Input: nums = [1,2,3,4], k = 1 Output: 0 Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.
Constraints:
1 <= nums.length <= 100
1 <= nums[i], k <= 100
Solutions
Solution 1: Enumeration
We first enumerate the index $j$ in the range $[0, n)$, and then enumerate the index $i$ in the range $[0, j)$. We count the number of pairs that satisfy $\textit{nums}[i] = \textit{nums}[j]$ and $(i \times j) \bmod k = 0$.
The time complexity is $O(n^2)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$.
Python3
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
ans = 0
for j, y in enumerate(nums):
for i, x in enumerate(nums[:j]):
ans += int(x == y and i * j % k == 0)
return ans
Java
class Solution {
public int countPairs(int[] nums, int k) {
int ans = 0;
for (int j = 1; j < nums.length; ++j) {
for (int i = 0; i < j; ++i) {
ans += nums[i] == nums[j] && (i * j % k) == 0 ? 1 : 0;
}
}
return ans;
}
}
C++
class Solution {
public:
int countPairs(vector<int>& nums, int k) {
int ans = 0;
for (int j = 1; j < nums.size(); ++j) {
for (int i = 0; i < j; ++i) {
ans += nums[i] == nums[j] && (i * j % k) == 0;
}
}
return ans;
}
};
Go
func countPairs(nums []int, k int) (ans int) {
for j, y := range nums {
for i, x := range nums[:j] {
if x == y && (i*j%k) == 0 {
ans++
}
}
}
return
}
TypeScript
function countPairs(nums: number[], k: number): number {
let ans = 0;
for (let j = 1; j < nums.length; ++j) {
for (let i = 0; i < j; ++i) {
if (nums[i] === nums[j] && (i * j) % k === 0) {
++ans;
}
}
}
return ans;
}
Rust
impl Solution {
pub fn count_pairs(nums: Vec<i32>, k: i32) -> i32 {
let mut ans = 0;
for j in 1..nums.len() {
for (i, &x) in nums[..j].iter().enumerate() {
if x == nums[j] && (i * j) as i32 % k == 0 {
ans += 1;
}
}
}
ans
}
}
C
int countPairs(int* nums, int numsSize, int k) {
int ans = 0;
for (int j = 1; j < numsSize; ++j) {
for (int i = 0; i < j; ++i) {
ans += (nums[i] == nums[j] && (i * j % k) == 0);
}
}
return ans;
}