Skip to content

Dsa Search Binary Bound

DodaTech 1 min read

In this tutorial, you'll learn about How to Fix Binary Search for Boundaries Errors. We cover key concepts, practical examples, and best practices.

Fix binary search for boundaries errors when first/last occurrence logic fails for missing target.

Quick Fix

Wrong

def first(a,t):
    l=0; r=len(a)-1
    while l<=r:
        m=l+(r-l)//2
        if a[m]>=t: r=m-1
        else: l=m+1
    return l

Returns insertion point when target not found, not -1.

def first(a,t):
    l=0; r=len(a)-1; res=-1
    while l<=r:
        m=l+(r-l)//2
        if a[m]==t: res=m; r=m-1
        elif a[m]>t: r=m-1
        else: l=m+1
    return res
def last(a,t):
    l=0; r=len(a)-1; res=-1
    while l<=r:
        m=l+(r-l)//2
        if a[m]==t: res=m; l=m+1
        elif a[m]>t: r=m-1
        else: l=m+1
    return res
[2,4,10,10,10,18,20], first(10)->2, last(10)->4. O(log n).

Prevention

For first occurrence: don't stop at match, continue searching left half. For last: continue right.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is boundary search?

Find first and last occurrence of target in sorted array with duplicates.

First occurrence?

When match found, save and search left half (r=m-1) for earlier occurrence.

Last occurrence?

When match found, save and search right half (l=m+1) for later occurrence.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro