Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: n, q ≤ 2·10⁵ operations of two kinds: add v to every a[l..r], and ask for sum a[l..r]. A Fenwick tree with two arrays supports both in O(log n): prefix(i) = sum1(i)·i − sum2(i).
Problem: n, q ≤ 2·10⁵ operations of two kinds: add v to every a[l..r], and ask for sum a[l..r]. A Fenwick tree with two arrays supports both in O(log n): prefix(i) = sum1(i)·i − sum2(i).
class RangeBIT:
def __init__(s, n): s.n = n; s.b1 = [0] * (n + 1); s.b2 = [0] * (n + 1)
def _add(s, b, i, v):
while i <= s.n: b[i] += v; i += i & -i
def _sum(s, b, i):
r = 0
while i > 0: r += b[i]; i -= i & -i
return r
def add(s, l, r, v):
s._add(s.b1, l, v); s._add(s.b1, r + 1, -v)
s._add(s.b2, l, v * (l - 1)); s._add(s.b2, r + 1, -v * r)
def prefix(s, i): return s._sum(s.b1, i) * i - s._sum(s.b2, i)
def query(s, l, r): return s.prefix(r) - s.prefix(l - 1)
t = RangeBIT(8)
t.add(2, 5, 3); t.add(4, 8, 2); t.add(1, 1, 7)
print(t.query(1, 8), t.query(3, 4), t.query(6, 6))What is printed?- A. 29 8 5
- B. 29 5 2
- C. 27 8 2
- D. 29 8 2
Correct answer: D. 29 8 2
b1 is a difference array of the values; b2 corrects the prefix formula so that prefix(i) = Σ_{j≤i} a[j]. After the updates the array (1-based) is 7, 3, 3, 5, 5, 2, 2, 2 → total 29, a[3] + a[4] = 3 + 5 = 8, a[6] = 2 (a naive simulation agrees). A plain prefix-sum array needs O(n) per update and a plain Fenwick tree handles only point updates; a lazy segment tree is the other O(log n) option.
More Coding Interview Problems questions
- Problem: For n = 2·10⁵, compute Σ over all subarrays of (max − min). Sum of maxima minus sum of minima, each via monotonic stacks with…
- Problem: Adjacent piles in a row are merged two at a time; merging costs the combined size. Minimise the total cost (interval DP over [i…
- Problem: Rain on a height grid flows to a neighbour with height ≤ the current cell. The west/north edge touches one sea, the east/south…
- Problem: A recursive routine splits a problem of size n into parts n/3 and 2n/3 and does n extra work: W(n) = W(n/3) + W(2n/3) + n. The…
- Problem: Find the bug: Dijkstra (finalising a node when it is popped) is run on a graph with one negative edge and compared with…
- Problem: Count integers in [1, N] whose decimal digits have no two adjacent equal digits, using digit DP with states (position, previous…