Data Structures & AlgorithmsModerateProduct Company SDE · binary search warm-up

Problem: For the sorted array [1, 2, 2, 2, 5, 7], how many values are at most 2? Run the code.

Problem: For the sorted array [1, 2, 2, 2, 5, 7], how many values are at most 2? Run the code.
import bisect
a = [1, 2, 2, 2, 5, 7]
print(bisect.bisect_right(a, 2))
What is printed?
  1. A. 3
  2. B. 4
  3. C. 2
  4. D. 5

Correct answer: B. 4

bisect_right returns the index just after the last 2, which is 4, and equals the count of elements at most 2. bisect_left would give 1 instead.

More Coding Interview Problems questions

Exams that ask this topic