Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find lowest index of a given value in a presorted array

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!

like image 567
mike Avatar asked Apr 13 '12 21:04

mike


2 Answers

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
like image 57
pepero Avatar answered Sep 20 '22 01:09

pepero


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
like image 29
Fred Foo Avatar answered Sep 19 '22 01:09

Fred Foo