Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: n ≤ 2·10⁵ values; count pairs i < j with (a[i] + a[j]) divisible by k. The O(n²) check times out; bucket by remainder and pair each value with earlier values of the complementary remainder.

Problem: n ≤ 2·10⁵ values; count pairs i < j with (a[i] + a[j]) divisible by k. The O(n²) check times out; bucket by remainder and pair each value with earlier values of the complementary remainder.
def pairs_div(a, k):
    cnt = [0] * k; res = 0
    for x in a:
        r = x % k
        res += cnt[(k - r) % k]; cnt[r] += 1
    return res
a = [2, 7, 5, 4, 3, 8, 10]
print(pairs_div(a, 5), sum((a[i] + a[j]) % 5 == 0 for i in range(7) for j in range(i + 1, 7)))
What is printed?
  1. A. 4 5
  2. B. 5 4
  3. C. 5 5
  4. D. 10 5

Correct answer: C. 5 5

Remainders mod 5: 2, 2, 0, 4, 3, 3, 0. Pairs: (2, 3)-type remainders 2 + 3: two 2s × two 3s = 4 pairs (2+3, 2+8, 7+3, 7+8), and the two multiples of 5 pair with each other (5 + 10) → 5, matching brute force. The extra % k maps remainder 0 to bucket 0 (not k). Counting ordered pairs would double to 10. O(n + k) versus O(n²) ≈ 2·10¹⁰ for n = 2·10⁵.

More Coding Interview Problems questions

Exams that ask this topic