← Walmart Labs Interview Insights
I knew binary search immediately but the duplicate part is where I fumbled a bit.
Use a modified binary search to find the leftmost occurrence of the target. When the target is found, continue searching in the left half to check for earlier occurrences. This ensures O(log n) time complexity even with duplicates.
Pro tip: Emphasize that this approach is optimal for large datasets and mention that it can be easily adapted to find the last occurrence or count occurrences. Also, clarify how you handle edge cases like empty arrays or target not present.
Confirm that the array is sorted, may contain duplicates, and that you need the first occurrence. Ask about edge cases: empty array, target not present, all elements are the target.
Select binary search over linear scan for efficiency. Explain that binary search can be modified to find the leftmost occurrence by continuing to search left even after finding the target.
Initialize low and high pointers. While low <= high, compute mid. If array[mid] < target, move low to mid+1; if array[mid] > target, move high to mid-1; if equal, record mid as a potential answer and move high to mid-1 to search left.
After the loop, return the recorded index if found, else return -1. Discuss how the algorithm handles duplicates and ensures the first occurrence is found.
State time complexity O(log n) and space O(1). Walk through the example to verify correctness, and consider additional test cases like target at the beginning or end.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.