Hey I had this question in an interview and was wondering what was the best way to solve it. So say you are given an array that is already sorted and you want to find the lowest index of some value x.
Here is a python/pseudocode of what I came up with, I am just wondering if there is a better way to go about it?
def findLowestIndex(arr, x):
index = binarySearch(0, len(arr), x)
if index != -1:
while index > 0:
if arr[index] == arr[index-1]:
index -= 1
else:
break
return index
Thanks!
Your method takes linear time in the worst case, which is when the count of
xs in the array is O(n).An O(lg n) solution can be obtained by changing the binary search itself to find the first
xin the array instead of just any one of them: