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
.
n
?
nums
array?
nums
array?
(i, j)
.k
that are larger than the length of the array.(i, j)
with 0 <= i < j < n
.nums[i] == nums[j]
.(i * j) % k == 0
.n
is relatively small (under a few thousand).nums
values reducing unnecessary multiplicative checks.def countPairs(nums, k):
n = len(nums)
count = 0
# Iterate through every pair (i, j) with 0 <= i < j < n
for i in range(n):
for j in range(i + 1, n):
if nums[i] == nums[j] and (i * j) % k == 0:
count += 1
return count
# Example usage
nums = [3, 1, 2, 2, 2, 1, 3]
k = 2
print(countPairs(nums, k)) # Output should be based on problem description
Given the constraints typically provided in such problems, (O(n^2)) should be efficient enough for (n \leq 1000). However, if (n) is significantly larger, alternative strategies might be required.
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?