All Occurrences Search
Find all indices where a target value appears in a sequence.
All Occurrences Search
All occurrences search returns every index where a target value appears. Unlike first or last occurrence, this algorithm scans the entire sequence and collects all matches.
This is useful when duplicates matter and you need complete information rather than a single position.
Problem
Given a sequence $A$ of length $n$ and a value $x$, find all indices $i$ such that
$$ A[i] = x $$
Return the list of all such indices. If no match exists, return an empty list.
Algorithm
Scan the entire sequence and collect matching indices.
all_occurrences_search(A, x):
result = empty list
for i from 0 to length(A) - 1:
if A[i] == x:
append i to result
return result
Example
Let
$$ A = [4, 2, 7, 2, 9, 2] $$
and
$$ x = 2 $$
The scan proceeds:
| step | index | value | match | result |
|---|---|---|---|---|
| 1 | 0 | 4 | no | [] |
| 2 | 1 | 2 | yes | [1] |
| 3 | 2 | 7 | no | [1] |
| 4 | 3 | 2 | yes | [1, 3] |
| 5 | 4 | 9 | no | [1, 3] |
| 6 | 5 | 2 | yes | [1, 3, 5] |
Return:
$$ [1, 3, 5] $$
Correctness
The algorithm checks every index exactly once. Each time $A[i] = x$, the index $i$ is recorded. Since no index is skipped, all valid positions are included. No incorrect indices are added because inclusion requires equality.
Complexity
| case | comparisons | time |
|---|---|---|
| best | $n$ | $O(n)$ |
| worst | $n$ | $O(n)$ |
Space usage depends on the number of matches $k$:
$$ O(k) $$
When to Use
Use all occurrences search when:
- duplicates are important
- you need full match positions
- building frequency maps or indexes
- preprocessing for further computation
In sorted data, binary search can be used first to find a range, then enumerate efficiently.
Implementation
def all_occurrences_search(a, x):
result = []
for i, value in enumerate(a):
if value == x:
result.append(i)
return result
func AllOccurrencesSearch[T comparable](a []T, x T) []int {
var result []int
for i, v := range a {
if v == x {
result = append(result, i)
}
}
return result
}