- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

2

- Related Questions & Answers
- 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
- Python program to find list of triplets for which i+j+k is not same as n
- Program to find array by swapping consecutive index pairs in Python
- Python – Elements with same index
- Program to find an element in list whose value is same as its frequency in Python
- Program to find out the index of the most frequent element in a concealed array in Python
- Python Pandas - Sort index values and also return the indices that would sort the index
- Program to find value for which given array expression is maximized in Python
- Find mismatch item on same index in two list in Python
- Write a program to find the index of particular element in an array in javascript?
- Python program to find k'th smallest element in a 2D array
- C# Program to find the smallest element from an array
- Dictionary with index as value in Python
- Insert to specific index for MongoDB array?

Advertisements