Fixed Point Problem
Description
LeetCode Problem 1064.
Given an array of distinct integers arr, where arr is sorted in ascending order, return the smallest index i that satisfies arr[i] == i. If there is no such index, return -1.
Example 1:
Input: arr = [-10,-5,0,3,7]
Output: 3
Explanation: For the given array, arr[0] = -10, arr[1] = -5, arr[2] = 0, arr[3] = 3, thus the output is 3.
Example 2:
Input: arr = [0,2,5,8,17]
Output: 0
Explanation: arr[0] = 0, thus the output is 0.
Example 3:
Input: arr = [-10,-5,3,4,7,9]
Output: -1
Explanation: There is no such i that arr[i] == i, thus the output is -1.
Constraints:
1 <= arr.length < 10^4-10^9 <= arr[i] <= 10^9
Follow up: The O(n) solution is very straightforward. Can we do better?
Solution
Approach: Binary Search
A linear scan works, but we can do better using the order of the array. The values are distinct integers in increasing order, so each step to the right increases the value by at least 1 while the index increases by exactly 1. In other words arr[i] - i never decreases.
So the indices split into two parts: first those with arr[i] < i, then those with arr[i] >= i. A fixed point (arr[i] - i == 0) can only be in the second part, and if there is one, the first index of the second part is one, and it is the smallest. Binary search for the first i with arr[i] >= i, then check whether arr[i] == i there; if not, there is no fixed point at all and the answer is -1.
Searching for the first index of the second part, instead of stopping at any i with arr[i] == i, is what gives the smallest index when several fixed points exist.
Complexity: O(log n) time and O(1) extra space.
class Solution:
def fixedPoint(self, arr: List[int]) -> int:
# The values are distinct integers in increasing order, so arr[i] - i never decreases.
# Binary search for the first i with arr[i] >= i; only there can arr[i] == i first hold.
lo, hi = 0, len(arr) - 1
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] >= mid:
hi = mid
else:
lo = mid + 1
return lo if arr[lo] == lo else -1