Fixed Point — LeetCode 1064 Python Solution

EasyLeetCode PremiumArrayBinary Search
Problem
#1064
Reading time
2 min

The 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.

Example

Input
arr = [-10,-5,0,3,7]
Output
3
Explanation
For the given array, arr[0] = -10, arr[1] = -5, arr[2] = 0, arr[3] = 3, thus the output is 3.

Python solution

Python
class Solution:
    def fixedPoint(self, arr: List[int]) -> int:
        left, right = 0, len(arr) - 1
        while left < right:
            mid = (left + right) >> 1
            if arr[mid] >= mid:
                right = mid
            else:
                left = mid + 1
        return left if arr[left] == left else -1

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1064. Fixed Point is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1064. Fixed Point?
LeetCode 1064. Fixed Point is rated Easy on LeetCode.
What topics does LeetCode 1064. Fixed Point cover?
LeetCode 1064. Fixed Point is tagged Array and Binary Search on LeetCode.
Is LeetCode 1064. Fixed Point a premium problem?
Yes. LeetCode 1064. Fixed Point is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview