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?- A. 3 3 2
- B. 4 3 1
- C. 3 4 2
- 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
- Problem: A segment tree stores (sum, best prefix, best suffix, best subarray) per node to answer 'maximum subarray sum inside a[l..r]'…
- Problem: Smallest period of a log pattern from its KMP prefix function: per = n − π[n − 1], and s is a whole repetition only if per…
- Problem: Find the longest string that is a prefix of s, a suffix of s, and also occurs somewhere strictly inside (not as the prefix or the…
- Problem: Count pairs i < j with a[i] XOR a[j] < 6 using a binary trie that stores subtree counts (4-bit values). python def countless(a…
- 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…