All problems
First and Last Occurrence
Problem
Find the first and last index of target in a sorted list using binary search.
Run the binary search twice: in one pass keep searching left after a match to find the first occurrence, and in the other keep searching right to find the last occurrence.
Return [first, last], or [-1, -1] when target is absent.
Hint
After a match, keep going left (or right) instead of returning immediately.
Test cases
case 1
in: [[5,7,7,8,8,10],8]
expected: [3,4]
case 2
in: [[5,7,7,8,8,10],6]
expected: [-1,-1]
case 3
in: [[],1]
expected: [-1,-1]
case 4
in: [[2,2],2]
expected: [0,1]
Starter codePython
def first_last_occurrence(nums, target):
# Your code here
pass4 test cases · run your code against them in the editor