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
Binary Search for Fixed Point-10idx: 0-5idx: 10idx: 23idx: 37idx: 4Step 1: mid=2, arr[2]=0 < 2Step 2: Search right, found 3=3!โŒ Eliminated (arr[i] < i region)โœ… Search region (potential fixed points)Search Direction
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!
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
28.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen