Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: A sorted list of ticket prices is searched with Python's bisect module.

Problem: A sorted list of ticket prices is searched with Python's bisect module.
from bisect import bisect_left, bisect_right
a = [10, 20, 20, 20, 35, 50]
print(bisect_left(a, 20), bisect_right(a, 20), bisect_left(a, 36), bisect_right(a, 5))
What is printed?
  1. A. 1 4 4 1
  2. B. 1 3 5 0
  3. C. 2 4 4 0
  4. D. 1 4 5 0

Correct answer: D. 1 4 5 0

bisect_left returns the first index whose value is ≥ x (1 for 20), bisect_right the first index whose value is > x (4, just past the last 20). 36 would be inserted before 50, at index 5; 5 goes before everything, index 0. bisect_right − bisect_left = 3 is the count of 20s. Each call is O(log n).

More Coding Interview Problems questions

Exams that ask this topic