Workspace Lower Bound Template
0d
DSA Cheat Sheets

Lower bound template

Find the first value at least the target in sorted input.

InvariantHalf-open intervalAnswer remains in [l,r]
TimeO(log n)Space O(1)

Python

def lower(a,x):
    l,r=0,len(a)
    while l<r:
        m=(l+r)//2
        if a[m]<x: l=m+1
        else: r=m
    return l

C++

int lower(const std::vector<int>& a,int x){int l=0,r=a.size();while(l<r){int m=l+(r-l)/2;if(a[m]<x)l=m+1;else r=m;}return l;}

Java

static int lower(int[] a,int x){int l=0,r=a.length;while(l<r){int m=l+(r-l)/2;if(a[m]<x)l=m+1;else r=m;}return l;}