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?
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 ]