Search code examples
binary-search

Find missing number in sorted array


Whats wrong with this code ? Not able able to search missing number in a consecutive array using binary search.

a = [1,2,3,4,5,7,8]

lent = len(a)
beg =0
end = lent-1

while beg < end:
    mid = (beg + end) / 2
    if (a[mid]-a[beg])==(mid - beg):
        beg = mid + 1
    else:
        end = mid -1
    if(beg == end):
        mid = (beg + end) / 2
        print "missing"
        print a[0]+ beg

Solution

  • Update #1: Yes, there was another one mistake. You're right. Here's updated version

    Try this variant:

    a = [1,2,3,4,5,7,8]
    
    lent = len(a)
    beg =0
    end = lent-1
    
    while beg < end:
        mid = (beg + end) / 2
        if (a[mid]-a[beg])==(mid - beg):
            beg = mid
        else:
            end = mid
        if abs(beg-end) <= 1:
            print "missing: %s" % (a[0] + max(beg, mid),)
    

    Result:

    missing: 6
    

    Also, try use functions, so you could easily test and debug your code on different lists:

    def find_missing(a):
        lent = len(a)
        beg =0
        end = lent-1
    
        while beg < end:
            mid = (beg + end) / 2
            if (a[mid]-a[beg])==(mid - beg):
                beg = mid
            else:
                end = mid
            if abs(beg-end) <= 1:
                return a[0] + max(beg, mid)
    
    a = [1,2,3,4,5,7,8]
    print find_missing(a)
    
    a = [1,3,4,5,6]
    print find_missing(a)
    
    a = [1,2,3,4,5,7,8,9,10]
    print find_missing(a)
    

    Result:

    6
    2
    6