Binary Search: First Occurrence

easy
Unit 1 · Hash Map0/3 to milestone

Given a list of integers sorted in ascending order (with possible duplicates), return the index of the first occurrence of target, or -1 if it's not there.

Your solution must run in O(log⁡n)O(\log n) time, so no scanning the list. Don't use the bisect module, either. Write the search yourself.

Example

first_occurrence([1, 2, 2, 2, 3, 5], 2)   # 1
first_occurrence([1, 2, 3], 4)            # -1
#binary-search#arrays3 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Binary Search: First Occurrence · TechGradify