#2183
Count Array Pairs Divisible by K
HardArrayHash TableMathCountingNumber TheoryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the properties of divisibility and the greatest common divisor (GCD) to efficiently count valid pairs without checking each pair explicitly. This reduces the time complexity significantly.
⚙️
Algorithm
4 steps- 1Step 1: Create a frequency array to count occurrences of each remainder when nums[i] is divided by k.
- 2Step 2: For each number in nums, calculate the required complement that would make the product divisible by k using the formula k / gcd(k, nums[i]).
- 3Step 3: Use the frequency array to find how many numbers can pair with the current number to form a valid product.
- 4Step 4: Update the frequency array as you process each number to avoid double counting.
solution.py15 lines
1# Full working Python code
2import math
3from collections import defaultdict
4
5def countPairs(nums, k):
6 count = 0
7 freq = defaultdict(int)
8 for num in nums:
9 required = k // math.gcd(k, num)
10 count += freq[required]
11 freq[num % k] += 1
12 return count
13
14# Example usage
15print(countPairs([1, 2, 3, 4, 5], 2)) # Output: 7ℹ
Complexity note: The time complexity is O(n) because we only traverse the array once, and the space complexity is O(n) due to the frequency map storing counts of remainders.
- 1Understanding the relationship between GCD and divisibility is crucial for optimizing the solution.
- 2Using a frequency map allows us to efficiently count potential pairs without nested loops.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.