Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the first and the last matching occurrence of an array in python?

There is a interview question from AirBNB:

You have a sorted array, and you want get the first index and the last index of the matching occurrence of an element by a function in python. If there is no match, return [-1.-1]. If there is a match, return [first_index,last_index].

This is my newbie solution, can anyone come up with a better one?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

By the way, this question is from TechLead DailyInterviewPro.

def solution(array,key):
    start_index = -1
    ending_index = -1
    if key not in array:
        return [start_index,ending_index]
    else:
        for i in range(len(array)):
            if array[i]==key:
                if start_index == -1:
                
                    start_index = i
                    ending_index = i
                else:
                    ending_index = i
                    
        return [start_index,ending_index]        

>Solution :

with one liner, using list.index function you can use

[-1, -1] if key not in array else [arrary.index(key),len(array)-array[::-1].index(key)-1 ]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading