Program to find smallest index for which array element is also same as index in Python

Suppose we have a list of elements called nums where all items are unique, and they are sorted in ascending order, we have to find the minimum i such that nums[i] = i. If we cannot find any solution, then return -1. We have to solve this problem in O(log(n)) time.

So, if the input is like nums = [-4, -1, 2, 3, 8], then the output will be 2, because both nums[2] = 2 and nums[3] = 3 but 2 is smaller.

Algorithm

To solve this, we will follow these steps ?

  • ret := -1, lhs := 0, rhs := size of nums - 1

  • while lhs ? rhs, do

    • mid := floor of (lhs + rhs) / 2

    • if nums[mid] is same as mid, then

      • ret := mid

    • if nums[mid] ? mid, then

      • rhs := mid - 1

    • otherwise,

      • lhs := mid + 1

  • return ret

Example

Let us see the following implementation to get better understanding ?

def solve(nums):
    ret = -1
    lhs = 0
    rhs = len(nums) - 1
    while lhs <= rhs:
        mid = (lhs + rhs) // 2
        if nums[mid] == mid:
            ret = mid
        if nums[mid] >= mid:
            rhs = mid - 1
        else:
            lhs = mid + 1
    return ret

nums = [-4, -1, 2, 3, 8]
print(solve(nums))
2

How It Works

The binary search approach works because:

  • If nums[mid] > mid, the target index must be on the left side

  • If nums[mid] < mid, the target index must be on the right side

  • If nums[mid] == mid, we found a match but continue searching left for the smallest index

Another Example

# Test with different cases
test_cases = [
    [-10, -5, 0, 3, 7],
    [0, 2, 5, 8, 17],
    [-10, -5, 3, 4, 7, 9]
]

for i, nums in enumerate(test_cases):
    result = solve(nums)
    print(f"Test {i+1}: {nums} ? {result}")
Test 1: [-10, -5, 0, 3, 7] ? 3
Test 2: [0, 2, 5, 8, 17] ? 0
Test 3: [-10, -5, 3, 4, 7, 9] ? 3

Conclusion

This binary search solution efficiently finds the smallest index where the array value equals the index in O(log n) time. The key insight is that the sorted nature of the array allows us to eliminate half the search space at each step.

Updated on: 2026-03-26T15:12:23+05:30

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements