Question presented to candidate: "How does binary search work, and what has to be true about the data for it to work? Please write it in Python and tell me its complexity."
What a strong answer should cover:
- The mechanism: keep
loandhi, check the middle, discard the half that cannot contain the target; stop when found or the range is empty. - The requirements: sorted (or monotonic) data, O(1) random access, known bounds and a consistent comparison โ and why a linked list does not qualify.
- O(log n) time with a concrete number (about 20 steps for a million items), O(1) space iteratively.
- Handles duplicates with lower and upper bound, and states the loop invariant to avoid off-by-one errors.
- Python specifics:
//for the midpoint, ints never overflow, and thebisectmodule (bisect_left,bisect_right,insort).
Code / implementation expected: Yes โ a correct iterative binary search in Python, ideally also the lower-bound variant.