Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: A Fenwick tree over a DIFFERENCE array supports 'add v to a[l..r]' and 'read a[i]' in O(log n) (1-indexed, all zeros initially).
Problem: A Fenwick tree over a DIFFERENCE array supports 'add v to a[l..r]' and 'read a[i]' in O(log n) (1-indexed, all zeros initially).
n = 8; bit = [0] * (n + 2)
def upd(i, v):
while i <= n: bit[i] += v; i += i & -i
def range_add(l, r, v): upd(l, v); upd(r + 1, -v)
def point(i):
s = 0
while i > 0: s += bit[i]; i -= i & -i
return s
range_add(2, 6, 5); range_add(4, 8, 3); range_add(1, 3, -2)
print(point(3), point(5), point(8))What is printed?- A. 5 8 3
- B. 3 5 3
- C. 3 8 0
- D. 3 8 3
Correct answer: D. 3 8 3
A prefix sum of the difference array is the element value: a[3] = 5 − 2 = 3, a[5] = 5 + 3 = 8, a[8] = 3. upd(r + 1, −v) cancels the addition after r (for r = 8 it falls outside the array and is skipped).
More Coding Interview Problems questions
- Problem: Point-update / range-maximum segment tree (iterative, size n = 8). python n = 8; t = [0] (2 n) def upd(i, v): i += n; t[i] = v…
- Mo's algorithm answers q offline range queries on an array of n elements by sorting queries into √n-sized blocks of their left ends. If…
- Problem: Edges arrive one by one; report the first edge that creates an ODD cycle (making the graph non-bipartite), using union-find with…
- Problem: Total weight of a MAXIMUM spanning tree (Kruskal with edges sorted in decreasing order). python edges =…
- Find the bug: Dijkstra (finalising a node when first popped) is run on a graph with a NEGATIVE edge. Compare with Bellman–Ford. python…
- Problem: Topological order produced by DFS (append a node after all its descendants, then reverse). python g = {0: [2, 1], 1: [3], 2: [3…