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))
- A. 2
- B. 4
- C. 1
- 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
- Problem: Arrange the numbers 3, 30, 34, 5, 9 so that the concatenation is the largest possible. Run the code and state the printed string…
- Problem: How many integers x with 1 <= x <= 100 satisfy x^3 ≡ x (mod 7)? python print(sum(1 for x in range(1, 101) if pow(x, 3, 7) == x %…
- Problem: What does the following print? python from math import lcm print(lcm(range(1, 11)))
- Problem: How many integers from 1 to 100 have exactly 3 positive divisors? python print(sum(1 for x in range(1, 101) if sum(1 for d in…
- Problem: Piles of stones are 3, 4 and 5. Two players alternately remove any positive number of stones from one pile, and whoever takes the…
- Problem: A subtraction game lets a player remove 1, 3 or 4 stones. Let g(n) be the Grundy number (mex of the Grundy values reachable in…