- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

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

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))

## Input

[-4, -1, 2, 3, 8]

## Output

2

- Related Articles
- Program to count index pairs for which array elements are same in Python
- Program to find out the index in an array where the largest element is situated in Python
- Program to find array by swapping consecutive index pairs in Python
- Program to find out the index of the most frequent element in a concealed array in Python
- Python Program to insert an element into the array at the specified index
- Write a program to find the index of particular element in an array in javascript?
- Python program to compute the power by Index element in List
- Python – Elements with same index
- Program to find index, where we can insert element to keep list sorted in Python
- Python program to find k'th smallest element in a 2D array
- JavaScript Program for Equilibrium index of an array
- Program to find maximum value at a given index in a bounded array in Python
- Delete array element in given index range [L – R] in C++ Program
- Find mismatch item on same index in two list in Python
- C# program to find the index of an element in a List

Advertisements