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

PythonServer Side ProgrammingProgramming

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
raja
Published on 11-Oct-2021 07:20:25
Advertisements