Lower bound
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Lower bound finds the first position in a sorted list where the value is at least as big as the one you ask about. It tells you where something would be inserted, or where a range begins, even when the exact value is missing.
Practical use cases
- Web app: Inserting a new score on a leaderboard. A game site keeps scores sorted. When a player finishes, the code finds the first position whose score is not lower than the new one and places the player there. The board stays in order without re-sorting thousands of entries.
- Web app: Events from a start time. A calendar page shows events from 3 pm onwards. The events are sorted by time, so the code finds the first event starting at or after 3 pm and lists everything from there. It does not read the morning events at all.
- System: Ready-made lower_bound in libraries. Standard libraries offer ready-made versions, such as lower_bound in C++. They return the correct position even when the value is absent. A news site can use this to open a feed at the first article newer than a chosen time and skip millions of older rows with a handful of checks.
The story: Where Does My Ticket Fit?
The cinema had its seat prices pinned in order: 10, 20, 20, 30, 40, 50 rupees. Zoya walked in with exactly 25 rupees. "Which is the cheapest seat I can still afford to look at upwards... no wait, I mean the first seat that costs 25 or more?" she asked the clerk.
There was no seat at 25, so a normal binary search would shrug and say "not found". But Zoya did not want a yes or no. She wanted a position: the first place in the sorted list where the price is not smaller than 25. Here it is the 30-rupee seat, at index 3.
The trick is to ask the same question at the middle every time: "Is this price 25 or more?" If yes, this seat might be the answer, so keep it and look to the left for something even earlier. If no, throw this seat and everything left of it away. When the window closes, you stand on the answer. This is called the lower bound. It always gives an answer from 0 up to n, where n means "everything is smaller".
How to spot this problem, and where you need it
You need the first item that is not smaller than a value, or the spot where a new value belongs in an already sorted list, and the exact value may not exist.
Signs you need it
- The problem says "first element greater than or equal to", "insert position", "ceiling" or "where would this go".
- A normal search returns "not found" but you actually want to know the nearest position or the next larger value.
- You re-sort the whole list after each insertion just to keep it in order.
Where to use it in a project
- Time-range filters in sorted logs, bookings or activity feeds where you need the starting point.
- Keeping sorted lists such as leaderboards, price ladders and schedules tidy when new items arrive.
The solution
Use binary search with a small twist. Keep a low and high edge. Look at the middle: if its value is smaller than the target, the answer is to the right, so move the low edge past it. Otherwise the middle could be the answer, so keep it and move the high edge to it. When the edges meet, that position is the lower bound.
Payoff: Before: scanning or re-sorting 10,000 scores per insert. After: about 14 checks to find the spot.
Explain it like I am 8
Line up kids by height. You ask, "Where is the first kid who is at least as tall as me?" You point at someone in the middle: "Taller than me? Then the answer is that kid or someone before." If shorter, the answer is after. You never have to meet every kid.
How it works, step by step
- Set
low = 0andhigh = n(one past the last item, so "nothing is big enough" is a possible answer). - While low < high, look at
mid. - If a[mid] >= target: mid could be the answer, so
high = mid. - Else (a[mid] < target): the answer is to the right, so
low = mid + 1. - When low meets high, that index is the lower bound: the first position with a value >= target.
The code in four languages
PHP
<?php
// First index whose value is >= $target (n when every value is smaller).
function lowerBound(array $a, int $target): int {
$low = 0;
$high = count($a); // one past the end on purpose
while ($low < $high) {
$mid = intdiv($low + $high, 2);
if ($a[$mid] >= $target) {
$high = $mid; // mid might be the answer: keep it
} else {
$low = $mid + 1; // too small: discard it and the left
}
}
return $low;
}
$prices = [10, 20, 20, 30, 40, 50];
echo lowerBound($prices, 25), "\n"; // 3 (the 30)
echo lowerBound($prices, 20), "\n"; // 1 (first of the two 20s)
echo lowerBound($prices, 99), "\n"; // 6 (everything is smaller)JavaScript
// First index whose value is >= target (n when every value is smaller).
function lowerBound(a, target) {
let low = 0;
let high = a.length; // one past the end on purpose
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (a[mid] >= target) {
high = mid; // mid might be the answer: keep it
} else {
low = mid + 1; // too small: discard it and the left
}
}
return low;
}
const prices = [10, 20, 20, 30, 40, 50];
console.log(lowerBound(prices, 25)); // 3 (the 30)
console.log(lowerBound(prices, 20)); // 1 (first of the two 20s)
console.log(lowerBound(prices, 99)); // 6 (everything is smaller)Java
public class Main {
// First index whose value is >= target (n when every value is smaller).
static int lowerBound(int[] a, int target) {
int low = 0;
int high = a.length; // one past the end on purpose
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid] >= target) {
high = mid; // mid might be the answer: keep it
} else {
low = mid + 1; // too small: discard it and the left
}
}
return low;
}
public static void main(String[] args) {
int[] prices = {10, 20, 20, 30, 40, 50};
System.out.println(lowerBound(prices, 25)); // 3 (the 30)
System.out.println(lowerBound(prices, 20)); // 1 (first of the two 20s)
System.out.println(lowerBound(prices, 99)); // 6 (everything is smaller)
}
}Go
package main
import "fmt"
// lowerBound returns the first index whose value is >= target (len(a) when every value is smaller).
func lowerBound(a []int, target int) int {
low := 0
high := len(a) // one past the end on purpose
for low < high {
mid := low + (high-low)/2
if a[mid] >= target {
high = mid // mid might be the answer: keep it
} else {
low = mid + 1 // too small: discard it and the left
}
}
return low
}
func main() {
prices := []int{10, 20, 20, 30, 40, 50}
fmt.Println(lowerBound(prices, 25)) // 3 (the 30)
fmt.Println(lowerBound(prices, 20)) // 1 (first of the two 20s)
fmt.Println(lowerBound(prices, 99)) // 6 (everything is smaller)
}Time: O(log n) · Extra space: O(1). The window halves each time, so even a million prices need only about 20 questions.
Watch out for
- Setting
high = n - 1and then being unable to return "past the end". - Writing
high = mid - 1in this version; that throws away a possible answer. - Using
<=in the loop condition withhigh = mid, which can loop forever.
Quick check
- lowerBound([10,20,20,30], 20) returns...
- 0
- 2
- 1
- If every value is smaller than the target, lower bound returns...
- -1
- 0
- n (one past the last index)
- When a[mid] >= target we set...
- low = mid + 1
- return mid
- high = mid