This problem asks to find the smallest index i
in a sorted array arr
such that arr[i] == i
. A simple linear scan would work, but the problem hints at a more efficient solution using binary search. This is possible because the array is sorted.
Approach:
We can leverage the sorted nature of the array. If arr[mid] >= mid
, it means that the fixed point (if it exists) must be in the left half or at mid
itself because the array is sorted in ascending order. If arr[mid] < mid
, then the fixed point (if it exists) must be in the right half. This allows us to perform a binary search.
Algorithm:
left = 0
and right = arr.length - 1
.left < right
:
mid = (left + right) / 2
(or (left + right) >> 1
for bitwise efficiency).arr[mid] >= mid
: The fixed point (if any) lies in the left half (including mid
), so update right = mid
.arr[mid] < mid
): The fixed point (if any) lies in the right half, so update left = mid + 1
.left
will point to the potential fixed point. Check if arr[left] == left
. If true, return left
; otherwise, return -1
.Time Complexity Analysis:
The solution uses binary search, which has a time complexity of O(log n), where n is the length of the array. This is significantly better than the O(n) time complexity of a linear scan.
Space Complexity Analysis:
The algorithm uses only a constant amount of extra space for variables like left
, right
, and mid
. Therefore, the space complexity is O(1).
Code Examples (with explanations inline):
The provided code examples in Python, Java, C++, Go, and TypeScript all implement the same algorithm. Let's examine the Python code in detail:
class Solution:
def fixedPoint(self, arr: List[int]) -> int:
left, right = 0, len(arr) - 1 # Initialize left and right pointers
while left < right: # Binary search loop
mid = (left + right) >> 1 # Calculate middle index efficiently (bitwise right shift)
if arr[mid] >= mid: # If arr[mid] is greater than or equal to mid
right = mid # Search in the left half
else: # Otherwise
left = mid + 1 # Search in the right half
return left if arr[left] == left else -1 # Return index if found, otherwise -1
The other languages' implementations follow the same logic with minor syntactic differences. They all achieve the same O(log n) time complexity and O(1) space complexity.