Classic binary search but the duplicates thing is a small wrinkle.
Use binary search to find any occurrence of the target in O(log n) time. Since the array is sorted and may contain duplicates, a standard binary search that returns when the target is found is sufficient; no need to find the first or last occurrence. Clearly state the algorithm, walk through an example, and analyze time and space complexity.
Pro tip: Mention that while duplicates don't affect the O(log n) guarantee for finding any index, if the interviewer later asks for the first or last occurrence, you would modify the binary search to continue searching left or right respectively. This shows you understand the nuances of binary search with duplicates.
Confirm that the array is sorted, may contain duplicates, and that any valid index is acceptable. Ask about edge cases like empty array or target not present.
Explain that binary search is ideal for O(log n) search in a sorted array. Since any index is acceptable, a standard binary search that returns upon finding the target works.
Initialize low and high pointers. While low <= high, compute mid, compare array[mid] with target, and adjust pointers accordingly. Return mid if found, else -1.
Pick a small array with duplicates and trace the algorithm to demonstrate correctness, showing how it handles duplicates and returns a valid index.
State time complexity O(log n) and space O(1). Discuss edge cases: empty array, single element, target smaller/larger than all elements, and all duplicates.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.