All problems
Count Occurrences in Sorted Array
Problem
Count how many times target appears in a sorted list using binary search.
Find the first and last occurrence with two bounded binary searches; the answer is last minus first plus one.
Return 0 when target is absent.
Hint
Count equals last index minus first index plus one.
Test cases
case 1
in: [[1,1,2,2,2,3],2]
expected: 3
case 2
in: [[1,2,3],4]
expected: 0
case 3
in: [[],5]
expected: 0
case 4
in: [[5,5,5,5],5]
expected: 4
Starter codePython
def count_occurrences(nums, target):
# Your code here
pass4 test cases · run your code against them in the editor