![]() |
VOOZH | about |
Given an array arr[] of distinct integers sorted in ascending order, the task is to find the First Fixed Point in the array. Fixed Point in an array is an index i such that arr[i] equals i. Note that integers in the array can be negative.
Note: If no Fixed Point is present in the array, print -1.
Examples:
Input: arr[] = [-10, -5, 0, 3, 7]
Output: 3
Explanation: The value at index 3 of array arr[] is 3, which is equal to the index.
Input: arr[] = [0, 2, 5, 8, 17]
Output: 0
Explanation: The value at index 0 of array arr[] is 0, which is equal to the index.
Input: arr[] = [-10, -5, 3, 4, 7, 9]
Output: -1
Explanation: No Fixed Point
Table of Content
The idea is to iterate through the given array and find the index of the first fixed point. To do so, start iterating from the 0th index, and for each index i, check if arr[i] == i, if so return i, else traverse through other indices. If no fixed point is present in the array arr[], return -1.
Below is the implementation of the above approach:
3
The array is sorted in ascending order and contains distinct elements. This allows us to use Binary Search to efficiently locate a fixed point.
At any index i, compare the value arr[i] with i:
arr[i] == i, then i is a fixed point.arr[i] < i, then for all indices to the left, arr[j] < j will also hold, so the fixed point (if any) must lie in the right half.arr[i] > i, then for all indices to the right, arr[j] > j will also hold, so the fixed point must lie in the left half.To find the first fixed point, whenever a match is found, we store the index and continue searching on the left side to check if a smaller index also satisfies the condition.
3