← LinkedIn Interview InsightsSoftware Engineer
My first instinct was to find any occurrence and then scan left and right, which is obviously O(n) and not what they want.
Use binary search twice: first to find the leftmost occurrence of the target, then to find the rightmost occurrence. Modify the standard binary search to continue searching even after finding the target, adjusting the search boundaries based on whether you need the first or last position. This ensures O(log n) time complexity.
Pro tip: Mention that you can implement a single helper function that takes a boolean flag to find either the first or last occurrence, reducing code duplication and potential errors. Also, clarify how you handle edge cases like an empty array or when the target is not present.
Confirm that the array is sorted in ascending order, may contain duplicates, and that the target may or may not exist. Discuss edge cases: empty array, target smaller than first element, target larger than last element.
Perform binary search; when target is found, record the index and continue searching in the left half to find an earlier occurrence. Return the recorded index if found, else -1.
Similarly, perform binary search; when target is found, record the index and continue searching in the right half to find a later occurrence. Return the recorded index if found, else -1.
If either search returns -1, return [-1, -1]. Otherwise, return [first, last]. Ensure the solution runs in O(log n) time and O(1) space.
Walk through examples: target present multiple times, target present once, target absent, empty array. Verify correctness and time complexity.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.