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.
Example 1:
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:
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 <= 1001 <= nums[i], k <= 100This approach involves iterating over all possible pairs (i, j) using nested loops and checking if the conditions are met.
This code iterates over all pairs (i, j) where 0 <= i < j < n and checks if the elements are equal and i*j is divisible by k. The counter increment occurs whenever both conditions are satisfied.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2).
Space Complexity: O(1), as only a constant amount of space is used.
Use a hashmap to count occurrences of elements. Check each pair using a single loop by jumping indices where same elements exist. This reduces the number of checks as repeated pairs can be calculated mathematically.
The C solution doesn't fully utilize the given approach of frequency counting, but similarly iterates through the pair calculations since hashmap isn't directly usable in C standard library.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2).
Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Brute Force Approach | Time Complexity: O(n^2). |
| HashMap Frequency Counting Approach | Time Complexity: O(n^2). |
Count Equal and Divisible Pairs in an Array | Brute Force | Optimal | Detailed Maths | Leetcode 2176 • codestorywithMIK • 5,338 views views
Watch 9 more video solutions →Practice Count Equal and Divisible Pairs in an Array with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor