Leetcode 2176. Count Equal and Divisible Pairs in an Array
Given a 0-indexed integer array nums
of size 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
.1 <= nums.length <= 100
and 1 <= nums[i] <= 100
.1 <= nums[i] <= 100
, all elements are positive integers.k
to be zero?
k >= 1
.(i, j)
with i < j
and check both conditions.nums.length <= 100
, which makes it feasible.(i, j)
, check if nums[i] == nums[j]
and (i * j) % k == 0
.public class Solution {
public int countPairs(int[] nums, int k) {
int count = 0;
int n = nums.length;
// Iterate over each pair (i, j)
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if nums[i] == nums[j] and (i * j) % k == 0
if (nums[i] == nums[j] && (i * j) % k == 0) {
count++;
}
}
}
return count;
}
}
n
times and the inner loop runs approximately n/2
times, leading to O(n^2)
.O(1)
, making the total complexity O(n^2)
.This is efficient given the constraints, as n
is at most 100, making it computationally feasible to use O(n^2)
approach.
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?