Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: A segment tree with lazy propagation supports 'add v to a[l..r]' and 'sum of a[l..r]' on an array of 8 zeros.
Problem: A segment tree with lazy propagation supports 'add v to a[l..r]' and 'sum of a[l..r]' on an array of 8 zeros.
N = 8
t, lz = [0] * (4 * N), [0] * (4 * N)
def push(x, l, r):
if lz[x]:
m = (l + r) // 2
for c, cl, cr in ((2*x, l, m), (2*x+1, m+1, r)):
t[c] += lz[x] * (cr - cl + 1); lz[c] += lz[x]
lz[x] = 0
def add(x, l, r, ql, qr, v):
if qr < l or r < ql: return
if ql <= l and r <= qr:
t[x] += v * (r - l + 1); lz[x] += v; return
push(x, l, r); m = (l + r) // 2
add(2*x, l, m, ql, qr, v); add(2*x+1, m+1, r, ql, qr, v)
t[x] = t[2*x] + t[2*x+1]
def query(x, l, r, ql, qr):
if qr < l or r < ql: return 0
if ql <= l and r <= qr: return t[x]
push(x, l, r); m = (l + r) // 2
return query(2*x, l, m, ql, qr) + query(2*x+1, m+1, r, ql, qr)
add(1, 0, N-1, 1, 5, 3); add(1, 0, N-1, 3, 7, 2); add(1, 0, N-1, 0, 2, -1)
print(query(1, 0, N-1, 2, 5), query(1, 0, N-1, 0, N-1))What is printed?- A. 20 22
- B. 14 24
- C. 17 22
- D. 18 25
Correct answer: C. 17 22
Final array: [−1, 2, 2, 5, 5, 5, 2, 2]. a[2..5] = 2 + 5 + 5 + 5 = 17 and the total is 22. A pending lazy tag must be pushed to both children before descending, or partial queries miss earlier updates.
More Coding Interview Problems questions
- Problem: Count inversions (i < j, a[i] > a[j]) with a Fenwick tree over values, scanning from the right. python def inversions(a): n =…
- Problem: Return the longest word that can be built one letter at a time from other words in the list (every prefix must be present); ties…
- Problem: s1[i] and s2[i] are declared equivalent letters (the relation is reflexive, symmetric and transitive). Replace every letter of…
- Problem: Find all roots that give a tree of minimum height, by repeatedly peeling off leaves. python def mht(n, edges): adj = [set() for…
- Problem: Build a Huffman code for symbol frequencies and report the total number of bits for the encoded message (Σ freq × code length)…
- Problem: Balloons span horizontal intervals [start, end]; an arrow shot at x bursts every balloon with start ≤ x ≤ end. Find the minimum…