← Sprinter Health Interview Insights
The naive loop solution pops into your head immediately and you have to actively stop yourself from writing it.
Use binary search to find the first and last occurrence of the target, then compute the count as last - first + 1. This achieves O(log N) time by leveraging the sorted property and avoiding linear scans.
Pro tip: Mention that you can use a single binary search to find any occurrence, then expand left and right with binary searches to find boundaries, but be careful about worst-case O(N) if the target appears many times. Instead, explicitly implement two binary searches for first and last occurrence to guarantee O(log N).
Confirm that the list is sorted, may contain duplicates, and that the target may or may not be present. Discuss edge cases like empty list, target smaller than all elements, or larger than all elements.
Modify standard binary search to find the leftmost index where the target appears. When the middle element equals the target, continue searching in the left half to find an earlier occurrence.
Similarly, modify binary search to find the rightmost index where the target appears. When the middle element equals the target, continue searching in the right half to find a later occurrence.
If either search returns -1 (target not found), return 0. Otherwise, return lastIndex - firstIndex + 1.
Explain that each binary search takes O(log N) time, so total time is O(log N) and space is O(1). Walk through a small example to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.