Data Structures & AlgorithmsVery hardProduct company OA
Problem: A segment tree stores (sum, best prefix, best suffix, best subarray) per node to answer 'maximum subarray sum inside a[l..r]' queries. What is printed?
Problem: A segment tree stores (sum, best prefix, best suffix, best subarray) per node to answer 'maximum subarray sum inside a[l..r]' queries. What is printed?
def node(x): return (x, x, x, x)
def merge(L, R):
s = L[0] + R[0]
pre = max(L[1], L[0] + R[1]); suf = max(R[2], R[0] + L[2])
best = max(L[3], R[3], L[2] + R[1])
return (s, pre, suf, best)
a = [2, -5, 3, -1, 4, -6, 2, 2]
n = len(a); size = 1
while size < n: size *= 2
NEG = (0, -10**9, -10**9, -10**9)
t = [NEG] * (2 * size)
for i, x in enumerate(a): t[size + i] = node(x)
for i in range(size - 1, 0, -1): t[i] = merge(t[2 * i], t[2 * i + 1])
def query(l, r, node_=1, nl=0, nr=None):
if nr is None: nr = size - 1
if r < nl or nr < l: return None
if l <= nl and nr <= r: return t[node_]
m = (nl + nr) // 2
A = query(l, r, 2 * node_, nl, m); B = query(l, r, 2 * node_ + 1, m + 1, nr)
return A if B is None else B if A is None else merge(A, B)
print(query(0, 7)[3], query(1, 4)[3], query(5, 7)[3], t[1][1])What is printed?- A. 7 6 4 3
- B. 6 7 2 2
- C. 6 6 4 3
- D. 6 6 2 3
Correct answer: C. 6 6 4 3
Merging two halves: prefix = max(L.pre, L.sum + R.pre), suffix symmetric, best = max(L.best, R.best, L.suf + R.pre) – the crossing case. a = [2, −5, 3, −1, 4, −6, 2, 2]: the whole array's best is 3 − 1 + 4 = 6; [1..4] also 6; [5..7] = 2 + 2 = 4; the root's best prefix is 2 − 5 + 3 − 1 + 4 = 3. Taking max(L.best, R.best) only loses every crossing subarray. O(log n) per query.
More Coding Interview Problems questions
- Problem: Smallest period of a log pattern from its KMP prefix function: per = n − π[n − 1], and s is a whole repetition only if per…
- Problem: Find the longest string that is a prefix of s, a suffix of s, and also occurs somewhere strictly inside (not as the prefix or the…
- Problem: Count pairs i < j with a[i] XOR a[j] < 6 using a binary trie that stores subtree counts (4-bit values). python def countless(a…
- Problem: For every contiguous block, score = (minimum of the block) × (sum of the block). Return the maximum score using a monotonic stack…
- Problem: Find the shortest substring of s that contains t as a SUBSEQUENCE (leftmost if several). Two pointers: scan forward to complete…
- Problem: Count monotone paths (right/down) in a grid with blocked cells. The first version builds the table as [[0] C] R – every row is…