Fixed Point - Problem

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.

A fixed point in an array is an index where the value equals the index itself.

Input & Output

Example 1 — No Fixed Point
$ Input: arr = [-1,0,3,5,9,12]
Output: -1
💡 Note: Check each index: arr[0]=-1≠0, arr[1]=0≠1, arr[2]=3≠2, arr[3]=5≠3, arr[4]=9≠4, arr[5]=12≠5. No fixed point exists.
Example 2 — Fixed Point Found
$ Input: arr = [0,2,3,4,5]
Output: 0
💡 Note: arr[0] = 0, which equals the index 0. This is the smallest (and only) fixed point.
Example 3 — Multiple Fixed Points
$ Input: arr = [-1,1,3,4]
Output: 1
💡 Note: arr[1] = 1, which equals the index 1. This is the only fixed point.

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
Fixed Point - Binary Search Solution INPUT Sorted Array (ascending) Index: 0 1 2 3 4 5 -1 0 3 5 9 12 Fixed Point Definition: arr[i] == i (value equals index) Index vs Value Check: i=0: arr[0]=-1 -1 != 0 i=1: arr[1]=0 0 != 1 i=2: arr[2]=3 3 != 2 i=3: arr[3]=5 5 != 3 i=4: arr[4]=9 9 != 4 i=5: arr[5]=12 12 != 5 No fixed point found! BINARY SEARCH ALGORITHM 1 Initialize Pointers left=0, right=n-1 2 Calculate Mid mid = (left + right) / 2 3 Compare arr[mid] with mid Check if fixed point 4 Adjust Search Range Move left or right pointer Search Steps: L=0, R=5, M=2 arr[2]=3 > 2 search left L=0, R=1, M=0 arr[0]=-1 < 0 search right L=1, R=1, M=1 arr[1]=0 < 1 search right L=2 > R=1 STOP! FINAL RESULT Output: -1 Meaning: No fixed point exists in the given array. Return -1 as specified. Time Complexity: O(log n) Space Complexity: O(1) Key Insight: Since the array is sorted and has distinct integers, if arr[mid] > mid, any fixed point must be to the LEFT of mid. If arr[mid] < mid, any fixed point must be to the RIGHT. This allows binary search to efficiently find the smallest fixed point in O(log n) time complexity. TutorialsPoint - Fixed Point | Binary Search Optimal Solution
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
32.0K Views
Medium Frequency
~15 min Avg. Time
850 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