Skip to content

1064. Fixed Point 👍

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int fixedPoint(vector<int>& arr) {
    int l = 0;
    int r = arr.size() - 1;

    // Since arr[i] is strictly increasing, arr[i] - i will also be increasing.
    // Therefore, binary search `arr` for the first arr[i] - i = 0.
    while (l < r) {
      const int m = (l + r) / 2;
      if (arr[m] - m >= 0)
        r = m;
      else
        l = m + 1;
    }

    return arr[l] == l ? l : -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int fixedPoint(int[] arr) {
    int l = 0;
    int r = arr.length - 1;

    // Since arr[i] is strictly increasing, arr[i] - i will also be increasing.
    // Therefore, binary search `arr` for the first arr[i] - i = 0.
    while (l < r) {
      final int m = (l + r) / 2;
      if (arr[m] - m >= 0)
        r = m;
      else
        l = m + 1;
    }

    return arr[l] == l ? l : -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def fixedPoint(self, arr: list[int]) -> int:
    l = 0
    r = len(arr) - 1

    # Since arr[i] is strictly increasing, arr[i] - i will also be increasing.
    # Therefore, binary search `arr` for the first arr[i] - i = 0.
    while l < r:
      m = (l + r) // 2
      if arr[m] - m >= 0:
        r = m
      else:
        l = m + 1

    return l if arr[l] == l else -1