ProgrammingHardAmazon OA · Flipkart coding round

Which Python construct is the most efficient way to test whether a sorted list `a` contains x in O(log n) time without building extra structures?

  1. A. x in a, because the in operator on lists uses binary search
  2. B. a.index(x), because index stops early on sorted data
  3. C. sum(1 for v in a if v == x), which is O(log n) on a sorted list
  4. D. bisect.bisect_left(a, x) followed by an equality check at that index

Correct answer: D. bisect.bisect_left(a, x) followed by an equality check at that index

bisect_left finds the first position where x could go in O(log n). Checking that the value at the position equals x confirms membership. The plain in operator and index are linear scans.

More Python Programming questions

Exams that ask this topic