Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to efficiently find the first index in an array of distinct numbers that is equal to the value at that index?

"""
This implementation demonstrates how 
to efficiently find the first index 
in a sorted array of distinct numbers that
is equal to the value at that index.

Example: 
array = [-5, -3, 0, 3, 4, 5, 9]
First idx matching value is 3 as 
array[3] = 3
Let n the size of the input sorted array
of distinct values.

Time complexity: O(nlog2(n))
Space complexity: O(1)
"""
from turtle import left


def index_equal_value(array):
    left_idx = 0
    right_idx = len(array) - 1

    while left_idx <= right_idx:
        middle_idx = left_idx + (right_idx-left_idx)//2
        middle_value = array[middle_idx]

        if middle_value < middle_idx:
            # Focus on later half of the array
            left_idx = middle_idx + 1
        elif middle_value == middle_idx and middle_idx == 0:
            return middle_idx
        elif middle_idx == middle_idx and array[middle_idx-1] < middle_idx-1:
            return middle_idx
        else:
            # Focus on left hand side of the array
            right_idx = middle_idx-1
    return -1


print(index_equal_value([-5, -3, 0, 3, 4, 5, 9]))  # 3
Comment

PREVIOUS NEXT
Code Example
Python :: python psycopg2 utf8 
Python :: convert string to operator python 
Python :: join pyspark stackoverflow 
Python :: only int validator PyQt 
Python :: bnbpay 
Python :: how to python hack 2021 course 
Python :: pandas select column by index 
Python :: firebase-admin python 
Python :: calculate the addition of two lists in python 
Python :: python find all positions of element in list 
Python :: python yyyymmdd 
Python :: discord python command alias 
Python :: create df from two arrays 
Python :: python for property in object 
Python :: subprocess the system cannot find the file specified 
Python :: python search for string in file 
Python :: float print format python 
Python :: how to create an empty 2d list in python 
Python :: get dictionary in array python by value 
Python :: install selenium python mac anaconda 
Python :: python sum of digits in a string 
Python :: python read file in string list 
Python :: pandas rename index values 
Python :: emacs region indent python 
Python :: when pyspark 
Python :: sqlalchemy delete by id 
Python :: list of files in python 
Python :: Goal Parser Python 
Python :: plot tf model 
Python :: python local server command 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =