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?- A. 6 5
- B. 5 5
- C. 5 6
- 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
- Problem: For every contiguous block, score = (minimum of the block) × (sum of the block). Return the maximum score using a monotonic stack…
- Problem: Find the shortest substring of s that contains t as a SUBSEQUENCE (leftmost if several). Two pointers: scan forward to complete…
- Problem: Count monotone paths (right/down) in a grid with blocked cells. The first version builds the table as [[0] C] R – every row is…
- Problem: Two versions of Dijkstra. The second marks a vertex as finished the moment it is first PUSHED and never updates it again. python…
- Problem: KMP pattern search instrumented to count fallback steps k = π[k − 1] (total over the whole text). What is printed (matches…
- Problem: Single machine, jobs (name, duration, due time); lateness = finish − due. Minimise the MAXIMUM lateness. Compare…