Question presented to candidate: "You are given a sorted array of distinct integers that has been rotated at an unknown point, like [4, 5, 6, 7, 0, 1, 2], and a target. Return its index or -1, in O(log n) time. Please code it in Python."
What a strong answer should cover:
- The key insight: at any midpoint at least one half is sorted, and
nums[lo] <= nums[mid]tells you which. - Correct range checks: search the sorted half only if the target lies within its end values, otherwise the other half.
- O(log n) time and O(1) space, plus the two-pass alternative (find the rotation point, then binary search one run).
- Edge cases: not rotated, one or two elements (the
<=), empty array, target absent. - The duplicates follow-up: shrink both ends when
nums[lo] == nums[mid] == nums[hi]; worst case O(n). - Python specifics: chained comparisons (
nums[lo] <= target < nums[mid]) for the range test,//for the midpoint, and whynums.indexis the O(n) brute force.
Clarifying questions expected:
- Are all values distinct?
- Should I return the index or just whether it exists?
- Can the array be empty or not rotated at all?
Code / implementation expected: Yes โ a one-pass O(log n) Python solution, tested on edge cases.