Clarify the problem constraints and expected complexity, then explain the binary search logic step by step, including how you maintain the search space and handle edge cases. Write clean, bug-free code and test with examples, discussing time and space complexity.
Pro tip: Always verify your binary search implementation with edge cases like empty arrays, single elements, and targets at boundaries; off-by-one errors are the most common pitfall. Mention that you consider using built-in functions like `bisect` in Python but would implement manually if asked.
Ask questions to understand input format, constraints, expected output, and whether the array is sorted or rotated. Confirm if duplicates are allowed and if the search should return any valid index or the first/last occurrence.
Describe binary search: maintain low and high pointers, compute mid, compare with target, and adjust pointers. Discuss how to handle variations like finding insertion point or rotated arrays.
Write clean code with meaningful variable names, using a while loop with low <= high. Ensure mid is calculated as low + (high - low) // 2 to avoid overflow.
Walk through a few test cases: target present, absent, empty array, single element, and target at boundaries. Verify the code returns correct results and handles edge cases.
State that time complexity is O(log n) and space complexity is O(1) for iterative approach. Mention that recursive approach uses O(log n) space due to call stack.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.