Upper bound
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Upper bound finds the first position in a sorted list where the value is strictly greater than the one you ask about. Together with lower bound, it marks both ends of a group of equal values.
Practical use cases
- Web app: Events up to 5 pm. An activity log is sorted by time. To count how many events happened up to and including 5 pm, the code finds the first event after 5 pm. Its position is exactly the number of earlier events, so the dashboard number comes out in a few checks.
- Web app: How many products cost at most Rs 999. A shop sorts products by price. The filter label "Up to Rs 999 (342 items)" is found by locating the first price above 999, because that position is the count of cheaper items. The sidebar loads quickly even on a catalogue of 5 lakh products.
- System: Percentile and rank calculations. To tell a student they scored better than 82 percent of the class, systems find the position just after their score in the sorted marks. That position gives the rank immediately, so hundreds of students can open their result at once without a slow query each.
The story: Strictly Greater Than
The cricket club kept a sorted list of scores: 10, 20, 20, 30, 40, 50. Aarav asked Mira, "How many players scored exactly 20?" Mira remembered her lower-bound trick: the first place where the score is 20 or more is index 1.
"Good," said Aarav, "but where do the 20s end?" Mira needed the first place where the score is more than 20, not "20 or more". One word changed: greater than instead of greater or equal. That seat is index 3, the score of 30.
Now the 20s live in the gap between the two answers: positions 1 and 2. Count them by subtracting: 3 minus 1 equals 2. This is the upper bound: the first position whose value is strictly bigger than the target. Lower bound and upper bound are twin brothers; they differ by one symbol, and together they answer "how many?" in logarithmic time.
How to spot this problem, and where you need it
You need to count or select everything up to and including a limit in sorted data, or find the first item strictly beyond it, without reading through the earlier items.
Signs you need it
- The problem says "first element greater than", "strictly greater", "how many are at most x" or "next larger".
- You use lower bound but get off-by-one counts when the value itself appears several times.
- You loop from the start counting items until you pass a limit, and it gets slower as the data grows.
Where to use it in a project
- Count badges on filters, such as "price up to X" or "posted before Y" on large sorted lists.
- Rank, percentile and "better than N percent" features on sorted scores.
The solution
Do binary search for the first item that is strictly greater than your value. If the middle item is less than or equal to the value, the answer is to the right, so move past it. Otherwise it could be the answer, so keep it and look left. The final position is the upper bound, and the number of items up to the value equals that position.
Payoff: Before: counting through up to 5 lakh rows for each badge. After: about 19 checks, and the number appears instantly.
Explain it like I am 8
In a line of kids sorted by age, the kids who are exactly 8 stand together. The "lower bound" points at the first 8-year-old. The "upper bound" points at the first kid who is older than 8, right after the last 8-year-old. Between the two pointers are all the 8s.
How it works, step by step
- Set
low = 0,high = n. - While low < high, look at the middle.
- If a[mid] > target (strictly bigger): it might be the answer, so
high = mid. - Else (smaller or equal):
low = mid + 1. Equal values are left behind! - When low meets high, you have the first value strictly bigger than the target. Occurrences =
upperBound - lowerBound.
The code in four languages
PHP
<?php
function lowerBound(array $a, int $target): int { // first value >= target
$low = 0; $high = count($a);
while ($low < $high) {
$mid = intdiv($low + $high, 2);
if ($a[$mid] >= $target) { $high = $mid; } else { $low = $mid + 1; }
}
return $low;
}
function upperBound(array $a, int $target): int { // first value > target
$low = 0; $high = count($a);
while ($low < $high) {
$mid = intdiv($low + $high, 2);
if ($a[$mid] > $target) {
$high = $mid; // strictly bigger: maybe the answer
} else {
$low = $mid + 1; // smaller OR equal: move past it
}
}
return $low;
}
$scores = [10, 20, 20, 30, 40, 50];
echo upperBound($scores, 20), "\n"; // 3
echo upperBound($scores, 5), "\n"; // 0
echo upperBound($scores, 20) - lowerBound($scores, 20), "\n"; // 2 players scored 20JavaScript
function lowerBound(a, target) { // first value >= target
let low = 0, high = a.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (a[mid] >= target) high = mid; else low = mid + 1;
}
return low;
}
function upperBound(a, target) { // first value > target
let low = 0, high = a.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (a[mid] > target) {
high = mid; // strictly bigger: maybe the answer
} else {
low = mid + 1; // smaller OR equal: move past it
}
}
return low;
}
const scores = [10, 20, 20, 30, 40, 50];
console.log(upperBound(scores, 20)); // 3
console.log(upperBound(scores, 5)); // 0
console.log(upperBound(scores, 20) - lowerBound(scores, 20)); // 2 players scored 20Java
public class Main {
static int lowerBound(int[] a, int target) { // first value >= target
int low = 0, high = a.length;
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid] >= target) high = mid; else low = mid + 1;
}
return low;
}
static int upperBound(int[] a, int target) { // first value > target
int low = 0, high = a.length;
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid] > target) {
high = mid; // strictly bigger: maybe the answer
} else {
low = mid + 1; // smaller OR equal: move past it
}
}
return low;
}
public static void main(String[] args) {
int[] scores = {10, 20, 20, 30, 40, 50};
System.out.println(upperBound(scores, 20)); // 3
System.out.println(upperBound(scores, 5)); // 0
System.out.println(upperBound(scores, 20) - lowerBound(scores, 20)); // 2 players scored 20
}
}Go
package main
import "fmt"
// lowerBound returns the first index whose value is >= target.
func lowerBound(a []int, target int) int {
low, high := 0, len(a)
for low < high {
mid := low + (high-low)/2
if a[mid] >= target {
high = mid
} else {
low = mid + 1
}
}
return low
}
// upperBound returns the first index whose value is > target.
func upperBound(a []int, target int) int {
low, high := 0, len(a)
for low < high {
mid := low + (high-low)/2
if a[mid] > target {
high = mid // strictly bigger: maybe the answer
} else {
low = mid + 1 // smaller OR equal: move past it
}
}
return low
}
func main() {
scores := []int{10, 20, 20, 30, 40, 50}
fmt.Println(upperBound(scores, 20)) // 3
fmt.Println(upperBound(scores, 5)) // 0
fmt.Println(upperBound(scores, 20) - lowerBound(scores, 20)) // 2 players scored 20
}Time: O(log n) · Extra space: O(1). Same halving as lower bound; only the comparison changes from >= to >.
Watch out for
- Mixing up the two: lower bound uses
>=, upper bound uses>. - Expecting the upper bound to point at the last 20. It points one after it.
- Forgetting that the answer can be n (when nothing is bigger).
Quick check
- upperBound([10,20,20,30], 20) returns...
- 1
- 2
- 3
- How do you count copies of x in a sorted list?
- upper - lower
- lower - upper
- upper + lower
- When a[mid] equals the target, upper bound sets...
- low = mid + 1
- high = mid
- return mid