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?- A. 4 5
- B. 5 4
- C. 5 5
- 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
- Problem: A divide-and-conquer routine makes 3 recursive calls on halves and does linear extra work: T(n) = 3T(n/2) + n. The code evaluates…
- Problem: A sliding-window routine has a while loop nested inside a for loop. For a 12 000-character string, how many inner (left-pointer)…
- Problem: Find the inefficiency: two BFS versions on an R × C open grid. One marks a cell visited when it is pushed, the other only when it…
- Problem: Find the bug: binary search for the LAST x in [lo, hi] with ok(x) true (here the largest x with x² ≤ 30). The first version uses…
- Problem: n ≤ 2·10⁵ meetings [s, e); choose the maximum number of non-overlapping ones. Compare three greedy orders: by end time, by start…
- Problem: A road network has weights 1..5 (n, m ≤ 2·10⁵). A candidate solution runs plain BFS and sets dist[v] = dist[u] + w the first time…