Find the range of indices containing all occurrences of a value in a sorted array.
Equal range search finds the contiguous range of indices where a value appears in a sorted array. It returns a pair of indices:
such that all elements equal to lie within this interval.
This operation combines lower bound and upper bound.
Problem
Given a sorted array of length and a value , find indices and such that:
If does not appear, return an empty range where .
Key Idea
Compute:
Then:
contains all occurrences of .
Algorithm
equal_range(A, x):
l = lower_bound(A, x)
r = upper_bound(A, x)
return (l, r)Example
Let
and
Then:
- lower bound =
- upper bound =
So the result is:
Interpretation
- Elements in are equal to
- Elements before are less than
- Elements from onward are greater than
This forms a clean partition of the array.
Correctness
Lower bound ensures:
Upper bound ensures:
Together:
- all indices in satisfy
- no index outside the range contains
Complexity
| operation | time |
|---|---|
| lower bound | |
| upper bound | |
| total |
Space:
Use Cases
- Count occurrences:
- Range queries in sorted arrays
- Deduplication boundaries
- Frequency counting without scanning
Implementation
def equal_range(a, x):
def lower_bound(a, x):
l, r = 0, len(a)
while l < r:
m = l + (r - l) // 2
if a[m] < x:
l = m + 1
else:
r = m
return l
def upper_bound(a, x):
l, r = 0, len(a)
while l < r:
m = l + (r - l) // 2
if a[m] <= x:
l = m + 1
else:
r = m
return l
l = lower_bound(a, x)
r = upper_bound(a, x)
return (l, r)func EqualRange(a []int, x int) (int, int) {
lower := func(a []int, x int) int {
l, r := 0, len(a)
for l < r {
m := l + (r-l)/2
if a[m] < x {
l = m + 1
} else {
r = m
}
}
return l
}
upper := func(a []int, x int) int {
l, r := 0, len(a)
for l < r {
m := l + (r-l)/2
if a[m] <= x {
l = m + 1
} else {
r = m
}
}
return l
}
l := lower(a, x)
r := upper(a, x)
return l, r
}