The O(log n) requirement is basically screaming 'binary search' at you, but the tricky part is you need two separate searches: one to find the leftmost occurrence and one for the rightmost.
Use two separate binary searches: one to find the leftmost occurrence of K and another to find the rightmost occurrence. Modify the standard binary search to continue searching even after finding K, moving left for the first occurrence and right for the last. This ensures O(log n) time and handles duplicates correctly.
Pro tip: Mention that you can avoid code duplication by writing a helper function that takes a boolean flag to decide whether to find the first or last occurrence. This shows clean code practices and awareness of maintainability.
Restate the problem to ensure understanding: sorted array, target K, return [first, last] indices or [-1, -1], O(log n) required. Ask about edge cases like empty array or K not present.
Perform binary search; when arr[mid] == K, record mid as a potential answer and move the right pointer to mid-1 to search for an earlier occurrence. Continue until left > right.
Similarly, when arr[mid] == K, record mid and move the left pointer to mid+1 to search for a later occurrence. Continue until left > right.
If either search fails to find K, return [-1, -1]. Otherwise, return the two recorded indices.
State that each binary search is O(log n), so overall O(log n) time and O(1) space. Walk through examples including duplicates and edge cases.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.