Data Structures & AlgorithmsVery hardProduct company OA

Problem: Count 'heavy pairs' i < j with a[i] > 2·a[j] in O(n log n) using a Fenwick tree over coordinate-compressed values (both x and 2x are compressed).

Problem: Count 'heavy pairs' i < j with a[i] > 2·a[j] in O(n log n) using a Fenwick tree over coordinate-compressed values (both x and 2x are compressed).
def reverse_pairs(a):
    vals = sorted(set(a + [2 * x for x in a]))
    idx = {v: i + 1 for i, v in enumerate(vals)}
    bit = [0] * (len(vals) + 1)
    def add(i):
        while i < len(bit): bit[i] += 1; i += i & -i
    def pref(i):
        s = 0
        while i: s += bit[i]; i -= i & -i
        return s
    c = 0
    for seen, x in enumerate(a):
        c += seen - pref(idx[2 * x])
        add(idx[x])
    return c
print(reverse_pairs([5, 3, 1, 4, 2]), reverse_pairs([2, 4, 3, 5, 1]), reverse_pairs([-4, -1, -3]))
What is printed?
  1. A. 3 3 2
  2. B. 4 3 1
  3. C. 3 4 2
  4. D. 3 3 0

Correct answer: A. 3 3 2

Scan left to right; for each x, the earlier elements greater than 2x are seen − (#earlier ≤ 2x), queried from the BIT; then insert x. Compressing 2x as well lets the threshold be looked up directly. [5, 3, 1, 4, 2]: (5, 1), (5, 2), (3, 1) → 3. [2, 4, 3, 5, 1]: 4, 3, 5 against 1 → 3 (2 > 2 is false). With negatives the inequality flips intuition: −4 > −6 and −1 > −6 → 2. Plain merge-sort inversion counting would use a[i] > a[j] and give different numbers.

More Coding Interview Problems questions

Exams that ask this topic