Data Structures & AlgorithmsVery hardProduct company OA

Segment tree for range-minimum with lazy range-add (the pending add stays at a node and is applied on the way up instead of being pushed down). After two range updates, what is printed?

Segment tree for range-minimum with lazy range-add (the pending add stays at a node and is applied on the way up instead of being pushed down). After two range updates, what is printed?
N = 8
mn = [0] * (4 * N); lz = [0] * (4 * N)
def build(node, l, r, a):
    if l == r: mn[node] = a[l]; return
    m = (l + r) // 2
    build(2 * node, l, m, a); build(2 * node + 1, m + 1, r, a)
    mn[node] = min(mn[2 * node], mn[2 * node + 1])
def upd(node, l, r, ql, qr, v):
    if qr < l or r < ql: return
    if ql <= l and r <= qr: mn[node] += v; lz[node] += v; return
    m = (l + r) // 2
    upd(2 * node, l, m, ql, qr, v); upd(2 * node + 1, m + 1, r, ql, qr, v)
    mn[node] = min(mn[2 * node], mn[2 * node + 1]) + lz[node]
def query(node, l, r, ql, qr):
    if qr < l or r < ql: return 10**9
    if ql <= l and r <= qr: return mn[node]
    m = (l + r) // 2
    return min(query(2 * node, l, m, ql, qr), query(2 * node + 1, m + 1, r, ql, qr)) + lz[node]
a = [5, 2, 7, 3, 8, 6, 4, 9]
build(1, 0, N - 1, a)
upd(1, 0, N - 1, 1, 4, 3)
upd(1, 0, N - 1, 3, 6, -4)
print(query(1, 0, N - 1, 0, 2), query(1, 0, N - 1, 2, 5), query(1, 0, N - 1, 5, 7), mn[1])
  1. A. 5 6 4 2
  2. B. 5 2 4 0
  3. C. 5 2 0 0
  4. D. 8 2 0 0

Correct answer: C. 5 2 0 0

After +3 on [1, 4] and −4 on [3, 6] the array is [5, 5, 10, 2, 7, 2, 0, 9]. A fully covered node gets the add in both mn and lz; a partially covered node recomputes min(children) + its own lz, and queries add every lz on the path – so no push-down is needed for add/min. Min of [0..2] = 5, [2..5] = 2, [5..7] = 0, root 0. Forgetting the ancestor lz in queries returns stale values such as 6 and 4. Each operation touches O(log n) nodes.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic