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])- A. 5 6 4 2
- B. 5 2 4 0
- C. 5 2 0 0
- 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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Four cities, symmetric distances; the bitmask DP (Held–Karp) is compared with the nearest-neighbour heuristic, both starting and ending at…
- Maximum-weight independent set on a tree (no two chosen nodes adjacent) by tree DP returning (best if u taken, best if u skipped)…
- BFS that also counts the number of shortest paths. What is printed (dist[7], ways[7], ways[6], ways[4])? python from collections import…
- Dijkstra with a binary heap and lazy deletion (no decrease-key; outdated entries are skipped when popped). What is printed (dist to E…
- AVL insertions (rotations labelled by imbalance case). What is printed (preorder, rotation cases in order, height in edges)? python class…
- B-tree with minimum degree t = 2 (a 2-3-4 tree, at most 3 keys per node) using the single-pass insertion that splits every FULL node on…