class Solution:
    def fixedPoint(self, arr: List[int]) -> int:
        for i in range(len(arr)):
            if arr[i] == i:
                return i
        return -1

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1)

Where nn is the length of the array arrarr.


class Solution:
    def binarySearch(self, l: int, r: int, arr: List[int]) -> int:
        if l > r:
            return -1
        m = l + (r - l) // 2

        if arr[m] < m:
            return self.binarySearch(m + 1, r, arr)
        if arr[m] > m:
            return self.binarySearch(l, m - 1, arr)
        left = self.binarySearch(l, m - 1, arr)
        return left if left != -1 else m

    def fixedPoint(self, arr: List[int]) -> int:
        return self.binarySearch(0, len(arr) - 1, arr)

Time & Space Complexity

  • Time complexity: O(log⁡n)O(\log n)
  • Space complexity: O(log⁡n)O(\log n)

Where nn is the length of the array arrarr.


class Solution:
    def fixedPoint(self, arr: List[int]) -> int:
        l, r = 0, len(arr) - 1
        res = -1
        while l <= r:
            m = l + (r - l) // 2
            if arr[m] == m:
                res = m
                r = m - 1
            elif arr[m] < m:
                l = m + 1
            else:
                r = m - 1
        return res

Time & Space Complexity

  • Time complexity: O(log⁡n)O(\log n)
  • Space complexity: O(1)O(1)

Where nn is the length of the array arrarr.


4. Binary Search (Lower Bound)

class Solution:
    def fixedPoint(self, arr: List[int]) -> int:
        l, r = 0, len(arr)
        while l < r:
            m = l + (r - l) // 2
            if arr[m] >= m:
                r = m
            else:
                l = m + 1
        return l if l < len(arr) and arr[l] == l else -1

Time & Space Complexity

  • Time complexity: O(log⁡n)O(\log n)
  • Space complexity: O(1)O(1)

Where nn is the length of the array arrarr.