Problem Description
Given a sorted array of distinct integers, find the smallest index i such that arr[i] == i. If no such index exists, return -1. An O(n) solution is straightforward, but the goal is to achieve better than linear time.
Key Insights
- The array is sorted and contains distinct integers.
- A fixed point is an index i where arr[i] equals i.
- The function f(i) = arr[i] - i is strictly increasing; this enables the use of a binary search.
- Use binary search to efficiently locate the fixed point in O(log n) time.
Space and Time Complexity
Time Complexity: O(log n)
Space Complexity: O(1)
Solution
The solution uses a binary search approach. We initialize two pointers, low and high, and compute the mid index. At each step, if arr[mid] equals mid, we found a fixed point and then search to the left to check if a smaller fixed point exists. If arr[mid] is less than mid, we discard the left portion by setting low to mid + 1. If arr[mid] is greater than mid, we discard the right portion by setting high to mid - 1. This leverages the strictly increasing property of arr[i] - i, ensuring an efficient search for the smallest fixed point.