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?
  1. A. 20 22
  2. B. 14 24
  3. C. 17 22
  4. 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

Exams that ask this topic