
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Smallest Index Where Array Element Equals 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
Advertisements