Data Structures & AlgorithmsVery hardProduct company OA

Problem: Count pairs i < j with a[i] XOR a[j] < 6 using a binary trie that stores subtree counts (4-bit values).

Problem: Count pairs i < j with a[i] XOR a[j] < 6 using a binary trie that stores subtree counts (4-bit values).
def count_less(a, k, B=4):
    root = [None, None, 0]
    def insert(x):
        cur = root
        for b in range(B - 1, -1, -1):
            bit = x >> b & 1
            if cur[bit] is None: cur[bit] = [None, None, 0]
            cur = cur[bit]; cur[2] += 1
    def query(x):
        cur, c = root, 0
        for b in range(B - 1, -1, -1):
            if cur is None: break
            xb, kb = x >> b & 1, k >> b & 1
            if kb == 1:
                if cur[xb] is not None: c += cur[xb][2]
                cur = cur[xb ^ 1]
            else:
                cur = cur[xb]
        return c
    total = 0
    for x in a:
        total += query(x); insert(x)
    return total
a = [5, 1, 9, 3, 12, 6]
print(count_less(a, 6), sum(1 for i in range(6) for j in range(i) if a[i] ^ a[j] < 6))
What is printed?
  1. A. 6 5
  2. B. 5 5
  3. C. 5 6
  4. D. 4 4

Correct answer: B. 5 5

Walk the trie along x's bits while comparing with k's bits from the top: where k has a 1, every stored y that matches x on this bit (XOR bit 0) is strictly smaller in XOR, so its whole subtree count is added, and the walk continues on the other child (XOR bit 1 = k's bit); where k has a 0, the XOR bit must be 0. Each query is O(bits), so n = 2·10⁵ values cost ~6·10⁶ steps. Here the trie and brute force both give 5.

More Coding Interview Problems questions

Exams that ask this topic