Problem

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 < nsuch that nums[i] == nums[j] and (i * j) is divisible by k.

Examples

Example 1:

1
2
3
4
5
6
7
8
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:

1
2
3
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

Solution

Method 1 - Iterate on pairs

To solve this problem, we need to iterate through the array to find pairs (i, j) such that:

  1. nums[i] == nums[j] (the elements at indices i and j are equal).
  2. (i * j) is divisible by k.

The approach involves:

  • Using nested loops to examine all (i, j) pairs (i < j).
  • For each pair, checking the two conditions (nums[i] == nums[j] and (i * j % k == 0)).
  • If both conditions are satisfied, increment a counter to record the pair.

Approach

  1. Initialisation: Start with ans = 0 to store the count of valid pairs.
  2. Iterate through array:
    • Use nested loops to check all pairs (i, j) such that i < j.
  3. Evaluate conditions:
    • nums[i] == nums[j]: Check if the elements are equal.
    • (i * j) % k == 0: Check if the product of the indices is divisible by k.
  4. Update result: Increment ans for every pair that meets both conditions.
  5. Return result: Return ans after checking all pairs.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {

    public int countPairs(int[] nums, int k) {
        int ans = 0;
        int n = nums.length;

        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (nums[i] == nums[j] && (i * j) % k == 0) {
                    ans++;
                }
            }
        }

        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def countPairs(self, nums: List[int], k: int) -> int:
        ans: int = 0
        n: int = len(nums)
        
        for i in range(n):
            for j in range(i + 1, n):
                if nums[i] == nums[j] and (i * j) % k == 0:
                    ans += 1
                    
        return ans

Complexity

  • ⏰ Time complexity: O(n^2). The solution involves a nested loop to compare all pairs, hence the time complexity is O(n^2) where n is the length of the input array.
  • 🧺 Space complexity: O(1). The space complexity is O(1) as no additional data structures are used (other than variables for computations).