Data Structures & AlgorithmsModerateTCS NQT · binary search warm-up

Problem: The prefix sums of [2, 5, 1, 7, 3] are stored in a list p. What is printed by the code, which finds the first index whose prefix sum is at least 10?

Problem: The prefix sums of [2, 5, 1, 7, 3] are stored in a list p. What is printed by the code, which finds the first index whose prefix sum is at least 10?
import bisect
from itertools import accumulate
a = [2, 5, 1, 7, 3]
p = list(accumulate(a))
print(bisect.bisect_left(p, 10))
  1. A. 2
  2. B. 4
  3. C. 1
  4. D. 3

Correct answer: D. 3

The prefix sums are 2, 7, 8, 15, 18, so the first value at least 10 is 15 at index 3. Binary search on a sorted prefix array runs in O(log n).

More Coding Interview Problems questions

Exams that ask this topic