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 < n
, such that nums[i] == nums[j]
and (i * j)
is divisible by k
.
Examples
Example 1:
|
|
Example 2:
|
|
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:
nums[i] == nums[j]
(the elements at indicesi
andj
are equal).(i * j)
is divisible byk
.
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
- Initialisation: Start with
ans = 0
to store the count of valid pairs. - Iterate through array:
- Use nested loops to check all pairs
(i, j)
such thati < j
.
- Use nested loops to check all pairs
- 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 byk
.
- Update result: Increment
ans
for every pair that meets both conditions. - Return result: Return
ans
after checking all pairs.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
. The solution involves a nested loop to compare all pairs, hence the time complexity isO(n^2)
wheren
is the length of the input array. - 🧺 Space complexity:
O(1)
. The space complexity isO(1)
as no additional data structures are used (other than variables for computations).