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 :: aioschedule python 
Python :: pearson corr 
Python :: button position python 
Python :: onlt int validator qt py 
Python :: python remove non empty read only directory 
Python :: how to give multiple option to the user and ask the same question again and again until the user tells one of the options 
Python :: anova in python 
Python :: tsv to csv python 
Python :: print no new line python 
Python :: load all csv files in a folder python pandas 
Python :: python pandas how to load csv file 
Python :: python input tuple from user 
Python :: primes in python 
Python :: neat python full form 
Python :: Running setup.py bdist_wheel for opencv-python: still running... 
Python :: python datetime from isoformat 
Python :: shuffle rows dataframe 
Python :: python round number numpy 
Python :: txt file duplicate line remover python 
Python :: Make solutions faster in python 
Python :: python open file same folder 
Python :: plotly not showing in colab 
Python :: number of total words in cell pandas 
Python :: how to get chat first name in telebot 
Python :: phi 
Python :: how do I run a python program on atom 
Python :: hide particular attribute in django admin 
Python :: goal parser 
Python :: get number of string python 
Python :: remover espaços string python 
ADD CONTENT
Topic
Content
Source link
Name
2+2 =