The core idea clicked pretty fast since the array is sorted, two binary searches gets you there.
Use binary search twice: once to find the leftmost occurrence of the target and once to find the rightmost occurrence. If the target is not found, return 0; otherwise, the count is rightmost - leftmost + 1. This approach runs in O(log n) time, which is optimal for a sorted array.
Pro tip: Clarify that you're assuming the array is sorted in ascending order and that duplicates are allowed. Also, mention that you can optimize by first checking if the target exists using a standard binary search, then finding the boundaries, but the two-pass approach is simpler and still O(log n).
Confirm the array is sorted, whether it's ascending or descending, and if duplicates are present. Ask about the expected time complexity and if the array can be empty.
Implement a modified binary search that continues searching left even after finding the target, to locate the first occurrence. Return -1 if not found.
Similarly, implement a modified binary search that continues searching right after finding the target, to locate the last occurrence. Return -1 if not found.
If either leftmost or rightmost is -1, return 0. Otherwise, return rightmost - leftmost + 1.
State that time complexity is O(log n) and space is O(1). Discuss edge cases like empty array, target not present, all elements equal to target.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.