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?
  1. A. 9 10 17 17
  2. B. 9 10 14 17
  3. C. 10 9 17 14
  4. 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

Exams that ask this topic