Fixed Point — LeetCode 1064 Python Solution
- Problem
- #1064
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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 -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(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.