← Sprinter Health Interview Insights
The O(log N) constraint is what makes this non-trivial.
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 the first occurrence and then another to find the last, or modify binary search to find the insertion point of target and target+1. Also, clarify edge cases like empty array or target not present.
Confirm the input is sorted, discuss handling of empty array, target not present, and potential duplicates. Ask about integer overflow or large inputs.
Explain that you'll perform two binary searches: one for the first occurrence and one for the last occurrence. Alternatively, use binary search to find the lower bound (first index where target appears) and upper bound (first index where target+1 appears).
For first occurrence: when target is found, continue searching left. For last occurrence: continue searching right. Or, implement a lower_bound function that returns the first index where element >= target, and call it for target and target+1.
If first occurrence is -1 (not found), return 0. Otherwise, count = last - first + 1. Ensure indices are within bounds.
State time complexity O(log N) and space O(1). Walk through examples like [1,2,2,2,3] with target 2, and edge cases like target not present or all elements equal.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.