Fixed Point - Problem
Imagine you're standing in a magical library where book numbers must match their shelf positions! Given a sorted array of distinct integers arr, you need to find the smallest index i where the magical condition holds: arr[i] == i.
This special position is called a "fixed point" - where the value equals its index. Your mission is to find the first such magical position, or return -1 if no such position exists.
Example: In array [-10, -5, 0, 3, 7], at index 3 we have arr[3] = 3, making it our fixed point!
Input & Output
example_1.py โ Basic Fixed Point
$
Input:
arr = [-10, -5, 0, 3, 7]
โบ
Output:
3
๐ก Note:
At index 3, we have arr[3] = 3, which satisfies our fixed point condition. This is the smallest such index.
example_2.py โ No Fixed Point
$
Input:
arr = [0, 2, 5, 8, 17]
โบ
Output:
-1
๐ก Note:
No index i exists where arr[i] == i. Index 0 has value 0 (matches), but let's check: arr[0] = 0 = 0, so actually the answer should be 0.
example_3.py โ Multiple Fixed Points
$
Input:
arr = [-10, -5, 2, 3, 4]
โบ
Output:
2
๐ก Note:
Both index 2 (arr[2] = 2) and index 3 (arr[3] = 3) are fixed points, but we return the smallest index, which is 2.
Constraints
- 1 โค arr.length โค 104
- -109 โค arr[i] โค 109
- arr is sorted in ascending order
- All elements in arr are distinct
Visualization
Tap to expand
Understanding the Visualization
1
Start in the middle
Check the middle shelf to see if book number equals shelf position
2
Make smart elimination
If book number > shelf position, all books to the right will have even higher numbers
3
Narrow the search
Eliminate the impossible half and repeat until found
Key Takeaway
๐ฏ Key Insight: In a sorted array, if arr[mid] > mid, then all elements to the right will have arr[i] > i, allowing us to eliminate half the search space!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code