Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 17, 2025 19:13
Show Gist options
  • Save tatsuyax25/12e6759121c3791a4e2110b61b28f6e9 to your computer and use it in GitHub Desktop.
Save tatsuyax25/12e6759121c3791a4e2110b61b28f6e9 to your computer and use it in GitHub Desktop.
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.
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var countPairs = function(nums, k) {
// Initialize a counter to keep track of pairs that satisfy the conditions
let count = 0;
// Loop through all possible values of i (starting from index 0)
for (let i = 0; i < nums.length; i++) {
// For each i, loop through all possible values of j (starting from i + 1)
for (let j = i + 1; j < nums.length; j++) {
// Check if the values at indices i and j are equal
if (nums[i] === nums[j]) {
// Check if the product of i and j is divisible by k
if ((i * j) % k === 0) {
// Increment the counter if both conditions are satisfied
count++;
}
}
}
}
// Return the total count of valid pairs
return count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment