Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: A segment tree stores range sums. How many nodes does the recursive query visit?
Problem: A segment tree stores range sums. How many nodes does the recursive query visit?
a = [1, 3, 5, 7, 9, 11, 13, 15]
visits = 0
def build(node, l, r, t):
if l == r: t[node] = a[l]; return
m = (l + r) // 2
build(2*node, l, m, t); build(2*node+1, m+1, r, t)
t[node] = t[2*node] + t[2*node+1]
def query(node, l, r, ql, qr, t):
global visits; visits += 1
if qr < l or r < ql: return 0
if ql <= l and r <= qr: return t[node]
m = (l + r) // 2
return query(2*node, l, m, ql, qr, t) + query(2*node+1, m+1, r, ql, qr, t)
t = [0] * 16; build(1, 0, 7, t)
print(query(1, 0, 7, 2, 6, t), visits)What is printed?- A. 45 15
- B. 45 9
- C. 40 9
- D. 45 7
Correct answer: B. 45 9
Sum of a[2..6] = 5 + 7 + 9 + 11 + 13 = 45. The query stops at nodes fully inside [2, 6] ([2,3], [4,5], [6,6]) or fully outside, so only O(log n) nodes are visited – here 9 out of 15. A naive loop would touch 5 elements but O(n) in general.
More Coding Interview Problems questions
- Problem: Count the board states reachable on a 2 × 2 sliding puzzle ('0' is the blank, which swaps with an adjacent tile), using BFS over…
- Problem: Find the earliest time when all employees are connected, given friendship logs (time, a, b) and n people. python def…
- Problem: Find a redundant edge that, when removed, leaves a tree (return the last such edge in input order). python def redundant(edges)…
- Problem: Return the alien-dictionary letter order from a sorted list of words (Kahn's algorithm, ties alphabetical). python import heapq…
- Problem: Count how many nodes are 'safe' (every path from them ends at a terminal node) in a directed graph. python def safe(g): color =…
- Problem: Find the minimum effort path in a grid where effort is the maximum absolute height difference between consecutive cells. python…