C++
algorithms
lower_bound
upper_bound
programming

How to use lower_boundupper_bound to find position of any number in array?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

In C++, the Standard Template Library (STL) provides lower_bound and upper_bound as efficient tools for searching within sorted arrays. Both functions use binary search internally, giving you O(log n) performance. Understanding how they differ and when to use each one is essential for solving search, counting, and insertion problems effectively. This article walks through the mechanics of both functions with concrete examples.

How lower_bound Works

The lower_bound function is declared in the <algorithm> header. It searches a sorted range and returns an iterator pointing to the first element that is not less than the target value. In other words, it finds the first position where the target could be inserted without breaking the sort order.

Syntax

cpp
#include <algorithm>

ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value);
  • first and last define the sorted range to search.
  • value is the target you are looking for.
  • The function returns an iterator to the first element >= value.

Example

cpp
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int main() {
6    std::vector<int> arr = {10, 20, 20, 20, 30, 40, 50};
7
8    auto it = std::lower_bound(arr.begin(), arr.end(), 20);
9    int index = it - arr.begin();
10
11    std::cout << "lower_bound of 20 is at index: " << index << std::endl;
12    // Output: lower_bound of 20 is at index: 1
13    return 0;
14}

Since the first 20 in the array sits at index 1, lower_bound returns an iterator pointing there. If the value does not exist in the array, lower_bound returns the position where it would be inserted.

How upper_bound Works

The upper_bound function is similar but returns an iterator pointing to the first element that is strictly greater than the target value.

Syntax

cpp
ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T& value);

Example

cpp
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int main() {
6    std::vector<int> arr = {10, 20, 20, 20, 30, 40, 50};
7
8    auto it = std::upper_bound(arr.begin(), arr.end(), 20);
9    int index = it - arr.begin();
10
11    std::cout << "upper_bound of 20 is at index: " << index << std::endl;
12    // Output: upper_bound of 20 is at index: 4
13    return 0;
14}

The first element strictly greater than 20 is 30 at index 4. This is the key difference between the two functions: lower_bound finds >= while upper_bound finds strictly >.

Using Both Together

Combining lower_bound and upper_bound unlocks several useful patterns.

Counting Occurrences of a Value

The distance between upper_bound and lower_bound gives you the count of a specific value in a sorted array.

cpp
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int main() {
6    std::vector<int> arr = {10, 20, 20, 20, 30, 40, 50};
7
8    auto low = std::lower_bound(arr.begin(), arr.end(), 20);
9    auto high = std::upper_bound(arr.begin(), arr.end(), 20);
10
11    int count = high - low;
12    std::cout << "20 appears " << count << " times" << std::endl;
13    // Output: 20 appears 3 times
14    return 0;
15}

You can also use std::equal_range which returns both iterators in a single call, performing two binary searches internally.

cpp
auto range = std::equal_range(arr.begin(), arr.end(), 20);
int count = range.second - range.first;

Finding Insertion Position

If you want to insert a new element while keeping the array sorted, lower_bound gives you the correct insertion point.

cpp
1std::vector<int> arr = {10, 30, 40, 50};
2int newVal = 25;
3
4auto pos = std::lower_bound(arr.begin(), arr.end(), newVal);
5arr.insert(pos, newVal);
6// arr is now {10, 25, 30, 40, 50}

Checking if a Value Exists

You can use lower_bound to perform a membership check by verifying that the returned iterator points to an element equal to your target.

cpp
auto it = std::lower_bound(arr.begin(), arr.end(), 25);
bool found = (it != arr.end() && *it == 25);

This is what std::binary_search does internally, but using lower_bound directly gives you the position as well.

Using Custom Comparators

Both functions accept an optional comparator for custom sort orders, such as descending arrays or sorting by a struct field.

cpp
1std::vector<int> desc = {50, 40, 30, 20, 10};
2
3auto it = std::lower_bound(desc.begin(), desc.end(), 30, std::greater<int>());
4int index = it - desc.begin();
5// index is 2, pointing to the first element not greater than 30

Common Pitfalls

  • Unsorted input: Both functions require the range to be sorted according to the comparator. Using them on unsorted data produces undefined behavior with no compiler warning.
  • Confusing the two: Remember that lower_bound finds >=, while upper_bound finds strictly >. Mixing them up leads to off-by-one errors.
  • Iterator arithmetic on non-random-access containers: The subtraction it - arr.begin() works in O(1) for vectors and arrays, but for std::set or std::list you should use std::distance instead.
  • Empty ranges: Both functions handle empty ranges correctly by returning last, but forgetting to check for this can cause dereferencing issues.

Summary

lower_bound and upper_bound are powerful STL functions that use binary search to locate positions in sorted arrays in O(log n) time. lower_bound finds the first element >= the target, while upper_bound finds the first element strictly > the target. Together they enable counting occurrences, finding insertion points, and performing membership checks efficiently. Always ensure your data is sorted before calling these functions, and use custom comparators when working with non-default sort orders.


Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms