Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Find the bug: a range-sum helper over a prefix array (pre[0] = 0, pre[i] = sum of the first i values) should return a[l] + … + a[r] (inclusive).
Problem: Find the bug: a range-sum helper over a prefix array (pre[0] = 0, pre[i] = sum of the first i values) should return a[l] + … + a[r] (inclusive).
a = [4, 2, 7, 1, 3] pre = [0] for x in a: pre.append(pre[-1] + x) def bad(l, r): return pre[r] - pre[l] def good(l, r): return pre[r + 1] - pre[l] print(bad(1, 3), good(1, 3), bad(0, 4), good(0, 4))What is printed?
- A. 9 10 17 17
- B. 9 10 14 17
- C. 10 9 17 14
- D. 10 10 17 17
Correct answer: B. 9 10 14 17
With a leading 0, pre[i] covers a[0..i−1], so the inclusive range [l, r] is pre[r + 1] − pre[l]. bad(1, 3) = pre[3] − pre[1] = 13 − 4 = 9 misses a[3] = 1 (the true sum 2 + 7 + 1 = 10); bad(0, 4) drops the last element (14 instead of 17). Off-by-one errors like this pass many tests where the last element happens to be 0.
More Coding Interview Problems questions
- Problem: Find the bug: a list of multiplier functions is built in a loop with lambdas. python fs = [lambda x: x i for i in range(1, 4)] gs…
- Problem: Find the bug: even values are removed from a list while iterating over that same list. python nums = [2, 4, 4, 6, 5, 8] for x in…
- Problem: n ≤ 2·10⁵ values; count pairs i < j with (a[i] + a[j]) divisible by k. The O(n²) check times out; bucket by remainder and pair…
- Problem: A divide-and-conquer routine makes 3 recursive calls on halves and does linear extra work: T(n) = 3T(n/2) + n. The code evaluates…
- Problem: A sliding-window routine has a while loop nested inside a for loop. For a 12 000-character string, how many inner (left-pointer)…
- Problem: Find the inefficiency: two BFS versions on an R × C open grid. One marks a cell visited when it is pushed, the other only when it…