← Grammarly Interview Insights
I knew binary search cold, or thought I did.
Start by clarifying the problem and edge cases, then present binary search as the optimal O(log n) solution. Walk through the standard search, then extend to variants like leftmost/rightmost insertion points, emphasizing how to adapt the binary search logic to handle duplicates and boundaries.
Pro tip: Mention that Python's bisect module provides built-in functions for these variants, but be prepared to implement them manually to demonstrate understanding. Also, discuss how these variants are used in real-world scenarios like maintaining sorted data or range queries.
Ask if the array can contain duplicates, if it's sorted ascending, and what to return if not found. Consider empty array, single element, target smaller/larger than all elements.
Use two pointers (low, high) and a while loop to find the target. Return index if found, else -1. Analyze time and space complexity.
Modify binary search to find the first index where target can be inserted to keep array sorted (i.e., first element >= target). Handle duplicates by continuing search on the left when equal.
Similarly, find the last index where target can be inserted (i.e., first element > target). Adjust condition to move right when equal.
Compare linear vs binary search, mention built-in functions (e.g., bisect_left, bisect_right), and give examples where these variants are useful (e.g., range queries, maintaining sorted lists).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.