Fixed Point in a Given Array in Javascript
1 min readMay 31, 2022
A value equal to its index
Approach 1: Linear Search
- Loop over the array and check if the element is equal to its index in the array
- If it's true, return the index. Else, return -1
Time Complexity: O(n)
Space Complexity: O(1)
Approach 2: Binary search
- Find the middle element of the array
- If the middle element is the fixed point, return the middle index
- If the index of middle + 1 element ≤ the value at the high index, search on the right side of the middle
- If the index of middle - 1 element ≥ the value at the low index, search on the left side of the middle
- Return -1 if no element is found
Time Complexity: O(log n)
Space Complexity: O(1)