Interview Q&A · C++ · 10 questions in this topic

STL Algorithms & Idioms — C++ Interview Q&A

All C++ topics

Thinking in algorithms — sorting, searching, remove-erase, lambdas with algorithms, and complexity guarantees. Part of STL Containers & Algorithms · 213 questions in the C++ bank.

Why should you use STL algorithms instead of hand-written loops?

Answer

Algorithms name intent (sort, find_if, transform vs an anonymous for), are reviewed and optimized once, compose with lambdas and execution policies, and eliminate off-by-one and invalidation mistakes. They also parallelize (C++17 execution policies) where hand loops would need rewriting.

Modern guidance: no raw loops for named operations — reach for the algorithm first.

Example

Example.cppcpp
#include <algorithm>
bool any_neg(const std::vector<int>& v) {
    return std::any_of(v.begin(), v.end(), [](int x) { return x < 0; });
}

💡 Name intent plus fewer bugs is the complete justification; parallel policies are the bonus.

What is the complexity of `std::sort` and is it stable?

Answer

std::sort averages O(n log n) (introsort: quicksort switching to heapsort past depth limits, insertion sort for tiny runs) and is not stable — equal elements may reorder. stable_sort preserves equal-element order at O(n log n) with O(n) extra memory (or O(n log²n) without). partial_sort handles top-k efficiently.

Sort requires random-access iterators, which is why list has its own member sort.

Example

Example.cppcpp
std::vector<int> v{3,1,2};
std::sort(v.begin(), v.end()); // not stable
std::stable_sort(v.begin(), v.end()); // stable, extra memory

How does binary search (`lower_bound`, `upper_bound`, `binary_search`) work in STL?

Answer

They operate on sorted ranges: lower_bound finds the first element not less than the value, upper_bound the first greater, binary_search just reports presence, equal_range returns both. All are O(log n) on random-access iterators (O(n) steps on weaker iterators) and require the same ordering used for sorting.

Calling them on unsorted data is silently wrong — no diagnostic.

Example

Example.cppcpp
std::vector<int> v{1, 2, 2, 5};
auto lo = std::lower_bound(v.begin(), v.end(), 2); // first 2
bool has = std::binary_search(v.begin(), v.end(), 5);

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits