Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Count how many times a value occurs in a sorted array in O(log n).

Problem: Count how many times a value occurs in a sorted array in O(log n).
from bisect import bisect_left, bisect_right
a = [2, 4, 4, 4, 4, 7, 9, 9]
print(bisect_right(a, 4) - bisect_left(a, 4), bisect_right(a, 5) - bisect_left(a, 5), bisect_left(a, 9))
What is printed?
  1. A. 4 0 7
  2. B. 4 0 6
  3. C. 3 0 6
  4. D. 4 1 6

Correct answer: B. 4 0 6

Occurrences = (first index > x) − (first index ≥ x). 4 occupies indices 1..4 → 4. 5 is absent so both bounds are 5 → 0. bisect_left(a, 9) is the first 9, index 6. Two binary searches: O(log n).

More Coding Interview Problems questions

Exams that ask this topic