STL algorithms and priority_queue: sort, lower_bound, heaps

Difficulty: Intermediate

Question

How do std::sort, std::lower_bound and upper_bound work, and what are their complexities? How do you create a min-heap with std::priority_queue and use a custom comparator?

Answer

For online assessments and coding rounds at companies like Amazon, DE Shaw and Goldman Sachs, fluency with these STL pieces saves you minutes on every problem. Let's go through them with the details interviewers probe.

std::sort sorts a range using a comparison function, by default operator<. It requires random-access iterators, so it works on vector, array and deque but not on list (which has its own member sort). The typical implementation is introsort, a hybrid of quicksort, heapsort and insertion sort, which guarantees O(n log n) even in the worst case. It is not stable: equal elements may change their relative order. If you need stability, use std::stable_sort, which is O(n log n) with extra memory (or O(n log^2 n) without). A comparator must define a strict weak ordering: comp(a, a) must be false, and it must be consistent. A comparator using <= violates this, and can cause undefined behaviour or crashes in sort, a classic bug.

std::lower_bound(first, last, value) performs a binary search on a sorted range and returns an iterator to the first element that is not less than the value, that is, greater than or equal to it. std::upper_bound returns an iterator to the first element strictly greater than the value. Both are O(log n) on random-access iterators. The pair gives you the count of a value: upper_bound minus lower_bound. To check for existence use std::binary_search, or check that lower_bound is not at the end and points to an equal element. The range must be sorted with the same comparator, otherwise the result is meaningless. Note that on a std::set or map you should use their member lower_bound, since the algorithm version on bidirectional iterators degrades to O(n) iterator steps.

std::priority_queue is a container adaptor, by default over a vector, that keeps the largest element on top: a max-heap. Push and pop are O(log n), top is O(1). Building a heap from n elements via the range constructor is O(n). It has no iteration and no way to change an arbitrary element. For a min-heap, the standard trick is to pass std::greater as the comparator: 'std::priority_queue<int, std::vector<int>, std::greater<int>> pq;'. Alternatively, push negated values (careful with overflow). For custom types, supply a functor or lambda type as the third template parameter, and remember the counterintuitive rule: the comparator says which element has lower priority, so priority_queue with std::less puts the largest on top, and greater puts the smallest on top.

Think of the heap as a hospital triage desk: whoever compares as most urgent is always at the front, and finding the next patient is cheap even as new ones arrive. Typical uses: top-K elements, merging K sorted lists, Dijkstra's algorithm, and scheduling.

Interview tips: know the emptiness precondition (top or pop on an empty queue is undefined behaviour), remember that sort on a vector of pairs sorts lexicographically by default, and mention that for top-K largest of a stream you keep a min-heap of size K, giving O(n log k).

Code examples

sort, lower_bound and a min-heap

#include <algorithm>
#include <functional>
#include <iostream>
#include <queue>
#include <vector>

int main() {
    std::vector<int> v{7, 1, 5, 3, 3};
    std::sort(v.begin(), v.end());                        // 1 3 3 5 7
    auto lo = std::lower_bound(v.begin(), v.end(), 3);    // first >= 3
    auto hi = std::upper_bound(v.begin(), v.end(), 3);    // first > 3
    std::cout << (lo - v.begin()) << " " << (hi - v.begin()) << " " << (hi - lo) << "\n";

    std::sort(v.begin(), v.end(), std::greater<int>());   // descending
    for (int x : v) std::cout << x << " ";
    std::cout << "\n";

    std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
    for (int x : {5, 1, 4}) minHeap.push(x);
    while (!minHeap.empty()) { std::cout << minHeap.top() << " "; minHeap.pop(); }
    std::cout << "\n";

    auto cmp = [](const std::pair<int,int>& a, const std::pair<int,int>& b) { return a.second > b.second; };
    std::priority_queue<std::pair<int,int>, std::vector<std::pair<int,int>>, decltype(cmp)> pq(cmp);
    pq.push({1, 30}); pq.push({2, 10}); pq.push({3, 20});
    std::cout << pq.top().first << "\n";                 // smallest second
}

lower_bound is at index 1, upper_bound at index 3, so value 3 occurs twice. The custom lambda comparator turns the heap into a min-heap on the second field.

Key points

Common follow-up questions

Interview tips

Concepts covered

std::sort, lower_bound, priority_queue, comparators, binary search

More C++ & STL questions