The Count Array Pairs Divisible by K coding problem asks you to find the number of pairs of indices (i, j) such that i < j and the product nums[i] * nums[j] is divisible by k. Given that the array can be very large, a simple O(N^2) check of all pairs is too slow.
Qualcomm and PayPal use the Count Array Pairs Divisible by K interview question to test your knowledge of Number Theory, specifically Greatest Common Divisor (GCD). It evaluates your ability to optimize a product-based divisibility condition using frequency maps of GCD values. It’s a "Hard" problem because it requires a deep mathematical insight to reach the optimal O(N * sqrt(K)) solution.
The problem uses GCD and Frequency Maps.
x in the array, its contribution to the product being divisible by k is captured by gcd(x, k).a and b form a valid pair if (gcd(a, k) * gcd(b, k)) % k == 0.nums = [1, 2, 3, 4, 5], k = 2
gcd(x, 2) for each x:
gcd(1, 2) = 1gcd(2, 2) = 2gcd(3, 2) = 1gcd(4, 2) = 2gcd(5, 2) = 1{1: 3, 2: 2}.(1, 2): 1 * 2 = 2 (Divisible by 2). Pairs = 3 * 2 = 6.(2, 2): 2 * 2 = 4 (Divisible by 2). Pairs = 2 * (2-1) / 2 = 1.
Total = 7.(a * b) % k == 0 is equivalent to checking if the product of their GCDs with k is divisible by k.i < j constraint correctly when using the map.Whenever a problem involves products and divisibility, always think about Greatest Common Divisor. It’s the most powerful tool for reducing large numbers into their "useful" factors relative to a target k.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Check If It Is a Good Array | Hard | Solve | |
| Maximum Element-Sum of a Complete Subset of Indices | Hard | Solve | |
| Find the Count of Numbers Which Are Not Special | Medium | Solve | |
| Find the Maximum Factor Score of Array | Medium | Solve | |
| Maximum Prime Difference | Medium | Solve |