File: fixed-point/solution.py

Date: 2026-06-06

Time: 16:51

fixed-point/solution.py

Purpose

This file solves LeetCode 1064 - Fixed Point: given a sorted array of distinct integers, find the smallest index i where arr[i] == i. It returns -1 if no such index exists. This is a premium/easy problem that tests whether the solver recognizes binary search applicability on a sorted array.

Key Components

fixedPoint(arr: List[int]) -> int — The sole exported function. Contract:

Patterns

Modified binary search with leftmost-match tracking. Rather than returning immediately when arr[mid] == mid, the function records the match in result and continues searching left (hi = mid - 1). This guarantees it finds the *smallest* fixed point, not just any fixed point.

The branching logic is:

| Condition | Action | Rationale |

|-----------|--------|-----------|

| arr[mid] >= mid | Search left (hi = mid - 1) | If arr[mid] > mid, all indices to the right are also too large (sorted + distinct means arr[j] >= arr[mid] + (j - mid) > j for j > mid). If arr[mid] == mid, there might still be a smaller fixed point to the left. |

| arr[mid] < mid | Search right (lo = mid + 1) | By the same sorted+distinct argument, all indices to the left also satisfy arr[j] < j. |

This collapses two cases (arr[mid] > mid and arr[mid] == mid) into a single branch, which is a common binary search idiom for finding the leftmost occurrence.

Dependencies

Flow

1. Initialize lo = 0, hi = len(arr) - 1, result = -1.

2. While the search window is non-empty (lo <= hi):

3. Return result (still -1 if no fixed point was found).

Invariants

Error Handling

None — the function trusts its caller to provide a valid sorted, distinct array. An empty array (len(arr) == 0) is handled implicitly: hi starts at -1, the loop never executes, and -1 is returned.