Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Use bisect to count how many readings lie in the closed range [2, 7].

Problem: Use bisect to count how many readings lie in the closed range [2, 7].
from bisect import bisect_left, bisect_right
a = [1, 2, 2, 2, 5, 7, 7, 9]
L, R = bisect_left(a, 2), bisect_right(a, 7)
print(L, R, R - L)
What is printed?
  1. A. 1 6 5
  2. B. 3 7 4
  3. C. 1 7 7
  4. D. 1 7 6

Correct answer: D. 1 7 6

bisect_left(a, 2) = 1 (the first 2) and bisect_right(a, 7) = 7 (just past the last 7), so the range [2, 7] holds 7 − 1 = 6 values: 2, 2, 2, 5, 7, 7. Using bisect_left for the right end would drop the 7s.

More Coding Interview Problems questions

Exams that ask this topic