First/last occurrence
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
In a sorted list with repeated values, you often need the first or last position of a value, not just any match. A small change to binary search keeps going after finding a match until it reaches the edge of the repeats.
Practical use cases
- Web app: Orders placed on a date. An admin report counts orders on 14 March from a list sorted by date. The code finds the first position of that date and the last, and the difference gives the count. With 2 lakh orders it takes about 36 checks rather than reading them all.
- Web app: Leaderboard ties. A quiz site shows how many players scored exactly 80. Scores are sorted, so the code finds where the 80s begin and where they end, then subtracts the two positions. Everyone in that range shares the rank, and nobody scrolls through thousands of rows.
- System: Database range queries. When you ask a database for rows with a value between two limits, it uses a sorted index to jump to the first match and then reads forward until the last. That jump is this same idea, and it keeps range queries fast on big tables.
The story: The Queue at the Ration Shop
At the ration shop, tokens were handed out in order: 1, 2, then a whole family collected four tokens, all numbered 4, then 7 and 9. Grandpa Bhaskar asked Mira, "Which spot in the line does the first token 4 stand in? And where does the family end?"
Mira tried her binary search. She opened the middle, saw a 4, and shouted, "Found!" But Grandpa smiled: "You found a 4. I asked for the first one." Which of the four had she touched? Maybe the second, maybe the third.
So Mira changed one tiny rule. When she hits a 4, she writes the position down but does not stop. To find the first 4 she keeps searching the left side, in case an earlier 4 exists. To find the last 4 she keeps searching the right side. When the search runs out, the note in her hand is the answer. And now she could also count them: last minus first, plus one.
How to spot this problem, and where you need it
The sorted data contains many equal values and you need the boundaries of a group, such as where a date, a score or a word starts and ends, or how many there are.
Signs you need it
- The problem asks for "first position", "last position", "leftmost", "rightmost" or "count of a value in a sorted array".
- A normal binary search finds a match but you get a random one among several equal ones, and your answer is off.
- You scan sideways from a found match to count duplicates, which gets slow when there are thousands of them.
Where to use it in a project
- Counting log lines, orders or events in a sorted list for a given day or status.
- Pagination and range filters where you need the exact starting point in sorted data.
The solution
Run binary search, but when you hit the value, do not stop. For the first position, remember this index and keep searching only the left half in case an earlier match exists. For the last position, remember it and keep searching the right half. When the search ends, your last remembered index is the boundary. Count equals last minus first plus one.
Payoff: Before: scanning thousands of duplicates one by one. After: about 18 checks per boundary, even among 2 lakh rows.
Explain it like I am 8
In a row of four identical red marbles, you tap one in the middle. You say, "There might be another red one on my left!" so you keep walking left until the colour changes. The last red marble you touched on the left side is the first of the group.
How it works, step by step
- Run a normal binary search with
low,highandmid. - When mid matches, save it as the answer instead of returning at once.
- To find the first, keep looking left:
high = mid - 1. To find the last, keep looking right:low = mid + 1. - Otherwise do the usual halving: too small discards the left, too big discards the right.
- When low passes high, the saved answer is your position (or -1 if never saved). Count = last - first + 1.
The code in four languages
PHP
<?php
// Position of the FIRST occurrence of $target in a sorted array, or -1.
function firstOccurrence(array $a, int $target): int {
$low = 0; $high = count($a) - 1; $ans = -1;
while ($low <= $high) {
$mid = intdiv($low + $high, 2);
if ($a[$mid] === $target) {
$ans = $mid; // remember it...
$high = $mid - 1; // ...but look further LEFT for an earlier one
} elseif ($a[$mid] < $target) {
$low = $mid + 1;
} else {
$high = $mid - 1;
}
}
return $ans;
}
// Position of the LAST occurrence.
function lastOccurrence(array $a, int $target): int {
$low = 0; $high = count($a) - 1; $ans = -1;
while ($low <= $high) {
$mid = intdiv($low + $high, 2);
if ($a[$mid] === $target) {
$ans = $mid;
$low = $mid + 1; // look further RIGHT for a later one
} elseif ($a[$mid] < $target) {
$low = $mid + 1;
} else {
$high = $mid - 1;
}
}
return $ans;
}
$a = [1, 2, 4, 4, 4, 4, 7, 9];
$first = firstOccurrence($a, 4);
$last = lastOccurrence($a, 4);
echo "first=$first last=$last count=" . ($last - $first + 1), "\n"; // first=2 last=5 count=4
echo firstOccurrence($a, 5), "\n"; // -1JavaScript
// Position of the FIRST occurrence of target in a sorted array, or -1.
function firstOccurrence(a, target) {
let low = 0, high = a.length - 1, ans = -1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (a[mid] === target) {
ans = mid; // remember it...
high = mid - 1; // ...but look further LEFT for an earlier one
} else if (a[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return ans;
}
// Position of the LAST occurrence.
function lastOccurrence(a, target) {
let low = 0, high = a.length - 1, ans = -1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (a[mid] === target) {
ans = mid;
low = mid + 1; // look further RIGHT for a later one
} else if (a[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return ans;
}
const a = [1, 2, 4, 4, 4, 4, 7, 9];
const first = firstOccurrence(a, 4);
const last = lastOccurrence(a, 4);
console.log('first=' + first + ' last=' + last + ' count=' + (last - first + 1)); // first=2 last=5 count=4
console.log(firstOccurrence(a, 5)); // -1Java
public class Main {
// Position of the FIRST occurrence of target in a sorted array, or -1.
static int firstOccurrence(int[] a, int target) {
int low = 0, high = a.length - 1, ans = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == target) {
ans = mid; // remember it...
high = mid - 1; // ...but look further LEFT for an earlier one
} else if (a[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return ans;
}
// Position of the LAST occurrence.
static int lastOccurrence(int[] a, int target) {
int low = 0, high = a.length - 1, ans = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == target) {
ans = mid;
low = mid + 1; // look further RIGHT for a later one
} else if (a[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return ans;
}
public static void main(String[] args) {
int[] a = {1, 2, 4, 4, 4, 4, 7, 9};
int first = firstOccurrence(a, 4);
int last = lastOccurrence(a, 4);
System.out.println("first=" + first + " last=" + last + " count=" + (last - first + 1)); // first=2 last=5 count=4
System.out.println(firstOccurrence(a, 5)); // -1
}
}Go
package main
import "fmt"
// firstOccurrence returns the position of the FIRST occurrence of target in a sorted slice, or -1.
func firstOccurrence(a []int, target int) int {
low, high, ans := 0, len(a)-1, -1
for low <= high {
mid := low + (high-low)/2
if a[mid] == target {
ans = mid // remember it...
high = mid - 1 // ...but look further LEFT for an earlier one
} else if a[mid] < target {
low = mid + 1
} else {
high = mid - 1
}
}
return ans
}
// lastOccurrence returns the position of the LAST occurrence.
func lastOccurrence(a []int, target int) int {
low, high, ans := 0, len(a)-1, -1
for low <= high {
mid := low + (high-low)/2
if a[mid] == target {
ans = mid
low = mid + 1 // look further RIGHT for a later one
} else if a[mid] < target {
low = mid + 1
} else {
high = mid - 1
}
}
return ans
}
func main() {
a := []int{1, 2, 4, 4, 4, 4, 7, 9}
first := firstOccurrence(a, 4)
last := lastOccurrence(a, 4)
fmt.Printf("first=%d last=%d count=%d\n", first, last, last-first+1) // first=2 last=5 count=4
fmt.Println(firstOccurrence(a, 5)) // -1
}Time: O(log n) · Extra space: O(1). Two halving searches, each about log n steps. A plain scan of the repeats could cost O(n).
Watch out for
- Returning at the first hit. That gives a match, not the first or the last.
- Forgetting to save the answer before moving
highorlow; the matching spot is then thrown away. - Searching an unsorted list. Equal values must sit together for this to work.
Quick check
- After finding a match while hunting the FIRST occurrence, what next?
- Move low to mid + 1
- Return mid immediately
- Save mid and move high to mid - 1
- First = 2 and last = 5. How many copies are there?
- 4
- 3
- 5
- What does the function return if the target never matches?
- -1, because nothing was saved
- The middle position
- The first position