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!
deferred detection of equality approach in binary search gives the smallest index, reducing equality branches.
def binary_search(low, high, target, array):
    while low < high:
        mid = low + (high - low) / 2
        if a[mid] < target:
            low = mid + 1
        else:
            high = mid
    if (array[low] == target) return low
    else return -1
                        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 x in the array instead of just any one of them:
def binary_search(x, a):
    lo = 0
    hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1
        elif a[mid] > x:
            hi = mid
        elif mid > 0 and a[mid-1] == x:
            hi = mid
        else:
            return mid
    return -1
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With