Coding Interview Patterns Module 2 – Interview toolkits in five languages
C++ toolkit for coding rounds
vector, priority_queue, set, map and <algorithm> for coding rounds, plus the overflow, lookup and input traps, each run with Clang, GCC and sanitizers.
What you will learn
- Use vector, priority_queue, set, map, unordered_map and the algorithm library the way interview solutions need them
- Catch overflow and memory bugs with the address and undefined-behaviour sanitizers
- Read large input fast with each standard library
- Check which C++20 and C++23 features your compiler and the platform support
Before you start
What you’ll learn · Before you start
What you will learn
- Use vector, priority_queue, set, map, unordered_map and the algorithm library the way interview solutions need them
- Catch overflow and memory bugs with the address and undefined-behaviour sanitizers
- Read large input fast with each standard library
- Check which C++20 and C++23 features your compiler and the platform support
Before you start
On this page
C++ gives a coding round a large and fast standard library: a max-heap, sorted sets and maps with ordered queries, hash maps and an algorithm library for sorting, searching and counting. It also accepts code that is wrong without a word: a lookup that inserts, an unsigned size that wraps around to 18,446,744,073,709,551,615, a sum that overflows into undefined behaviour: In C and C++, an operation on which the standard places no requirement at all, such as shifting an int by 32 places. The compiler may assume it never happens, so no result can be relied on. More in “Bits across languages”, and input that is slow by default.
The sections below go through the containers and algorithms interview solutions use, reproduce each trap with the address and undefined-behaviour sanitizers switched on, measure the input methods with two standard libraries, and show how to tell which C++23 features your compiler really has. Every program here was built with Apple clang 21.0.0 and GCC 16.2.0.
A heap, sorted sets and maps, and a hash map cover most solutions
One program uses the containers that most solutions need. It is built with both compilers, which print the same lines:
#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
int main() {
// priority_queue gives the largest element first; std::greater<> turns it into a min-heap.
std::vector<int> scores = {40, 75, 62, 90};
std::priority_queue<int> largest(scores.begin(), scores.end());
std::priority_queue<int, std::vector<int>, std::greater<>> smallest(scores.begin(), scores.end());
std::cout << "largest " << largest.top() << ", smallest " << smallest.top() << '\n';
// A min-heap of (distance, node) pairs, as Dijkstra's algorithm uses it.
std::priority_queue<std::pair<int, char>, std::vector<std::pair<int, char>>, std::greater<>> frontier;
frontier.push({7, 'c'});
frontier.push({2, 'a'});
frontier.push({7, 'b'});
while (!frontier.empty()) {
auto [dist, node] = frontier.top();
frontier.pop();
std::cout << node << dist << ' ';
}
std::cout << '\n';
// set and map keep keys sorted; their member lower_bound finds the first key not less than x in O(log n).
std::set<int> slots = {9, 11, 14};
auto next = slots.lower_bound(12);
std::cout << "first slot at or after 12: " << *next << ", before it: " << *std::prev(next) << '\n';
// unordered_map counts in average O(1); copy to a vector to sort the result.
std::unordered_map<std::string, int> counts;
for (std::string w : {"pear", "fig", "pear", "apple", "fig", "pear"}) ++counts[w];
std::vector<std::pair<std::string, int>> byCount(counts.begin(), counts.end());
std::ranges::sort(byCount, [](const auto& a, const auto& b) {
return a.second != b.second ? a.second > b.second : a.first < b.first;
});
for (const auto& [word, n] : byCount) std::cout << word << '=' << n << ' ';
std::cout << '\n';
} """Runs shell commands as you would type them in a terminal, and prints the session.
Each line of the script is one command. The session shows it after "$ ", then what it printed (standard output and
standard error together, as a terminal shows them), and, when the command fails, its exit status. A sanitizer report
is cut to its summary lines, and file paths in it to their last part, because the rest (addresses, process numbers,
the folders of the compiler) changes from run to run and from one computer to another.
"""
import os
import re
import subprocess
# Homebrew's folders (Apple silicon, then Intel Macs): the gcc formula installs g++-16 there.
HOMEBREW_BIN = ["/opt/homebrew/bin", "/usr/local/bin"]
REPORT_START = re.compile(r"^(?:=+|==\d+==.*)$")
ABSOLUTE_PATH = re.compile(r"(?:/[^/\s:]+)+/([^/\s:]+)")
def short_paths(line: str) -> str:
return ABSOLUTE_PATH.sub(r"\1", line)
def tidy(output: str) -> list[str]:
lines = []
in_report = False
for line in output.splitlines():
if REPORT_START.match(line):
in_report = True
if "runtime error:" in line or line.startswith("SUMMARY:"):
lines.append(short_paths(line))
elif not in_report:
lines.append(line)
return lines
def run(script: str) -> None:
env = dict(os.environ)
env["PATH"] = os.pathsep.join([env.get("PATH", ""), *HOMEBREW_BIN])
for command in script.strip().splitlines():
command = command.strip()
if not command:
continue
print(f"$ {command}")
result = subprocess.run(command, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
for line in tidy(result.stdout):
print(line)
if result.returncode != 0:
print(f"[exit status {result.returncode}]") from session import run
# Built and run with both compilers.
run("""
clang++ -std=c++23 -Wall -Wextra containers.cpp -o containers && ./containers
g++-16 -std=c++23 -Wall -Wextra containers.cpp -o containers-gcc && ./containers-gcc
""") Output
$ clang++ -std=c++23 -Wall -Wextra containers.cpp -o containers && ./containers largest 90, smallest 40 a2 b7 c7 first slot at or after 12: 14, before it: 11 pear=3 fig=2 apple=1 $ g++-16 -std=c++23 -Wall -Wextra containers.cpp -o containers-gcc && ./containers-gcc largest 90, smallest 40 a2 b7 c7 first slot at or after 12: 14, before it: 11 pear=3 fig=2 apple=1
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 containers_session.py
std::priority_queueis a max-heap: A binary tree kept in an array in which every parent is at least as large as its children, so the largest element is at the front: reading it costs O(1), and adding or removing an element O(log n).. Its default comparison isstd::less, sotop()is the largest element. Passingstd::greater<>as the third template argument makes the smallest element the top, which Dijkstra’s algorithm and “k smallest” problems need. Pairs compare by their first member, then the second, so{7, 'b'}came out before{7, 'c'}.std::setandstd::mapkeep keys sorted and answer ordered questions:lower_bound(12)is the first key not less than 12, andstd::prevof it is the key just below. Astd::mapis a sorted map: A map that keeps its keys in sorted order while entries are added and removed, so it can give the smallest key, the largest, or the nearest one above or below a value, each in O(log n). Java's TreeMap and C++'s std::map are sorted maps. More in “Choosing your interview language”.std::unordered_mapcounts with++counts[w]in average O(1). It has no order, so copy it to a vector and sort when the output must be ordered;std::ranges::sortwith a comparator sorts by count, then by word.
A priority_queue is a vector arranged as a heap. Its range constructor calls std::make_heap, top() reads the
first position, and each pop() calls std::pop_heap, which moves the largest element to the back before the vector
drops it. Step through the same work on the program’s four scores, 40, 75, 62 and 90: the heap is built with 90 at the
root, and each step after that moves the largest value left to the end, as a pop() does:
- being compared or looked at
- being moved or written
- the key, pivot or target
Pseudo-code
-
build a max-heap from a (bottom-up) -
for end from n − 1 down to 1: -
swap a[0] and a[end] (the largest goes to its final place) -
siftDown(0) in a[0..end − 1]
Heap sort: first arrange the 4 values as a max-heap (every parent at least its children), then move the root, the largest value left, to the end, 3 times.
When it finishes: Sorted: 40 62 75 90.
Try your own input
The build leaves 90 at the root, the top() that the program printed as “largest 90”. The steps after it are
std::sort_heap, which is std::pop_heap repeated, so they leave the four scores in increasing order. With
std::greater<> every comparison is reversed and the smallest score, 40, stays at the root, which is why
smallest.top() printed 40.
The costs the standard requires of each container are listed in the DSA toolkit lesson.
Checkpoint
Check: The heap, sorted and hashed containers a round uses
Search a set with its own member: O(log n) instead of a walk
std::lower_bound is a binary search, but on a std::set it walks: cppreference’s page on it notes that for
iterators that are not random access, the number of iterator increments is linear, and that the member lower_bound
of set and map should be preferred. The difference is easy to miss in a code review and impossible to miss in a
time limit.
#include <algorithm>
#include <chrono>
#include <iostream>
#include <set>
// 500 queries for "the first element at or after x" in a set of 100,000 even numbers, two ways.
int main() {
std::set<int> s;
for (int i = 0; i < 100'000; ++i) s.insert(2 * i);
auto timed = [](const char* label, auto&& query) {
auto start = std::chrono::steady_clock::now();
long long total = 0;
for (int x = 1; x < 200'000; x += 400) total += query(x);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start);
std::cout << label << "total " << total << ", " << ms.count() << " ms\n";
};
timed("s.lower_bound(x): ", [&](int x) { return *s.lower_bound(x); });
timed("std::lower_bound(s.begin(), ...): ", [&](int x) { return *std::lower_bound(s.begin(), s.end(), x); });
} from session import run
run("""
clang++ -std=c++23 -O2 -Wall -Wextra set_search.cpp -o set_search && ./set_search
""") Output
$ clang++ -std=c++23 -O2 -Wall -Wextra set_search.cpp -o set_search && ./set_search s.lower_bound(x): total 49901000, 0 ms std::lower_bound(s.begin(), ...): total 49901000, 977 ms
This output changes from run to run: the times depend on the computer and on what else it is running
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 search_session.py
Both find the same elements. The member function takes O(log n) per query; std::lower_bound makes O(log n)
comparisons, but a set’s iterator moves one element at a time, so every jump of its binary search is a walk. An
iterator that counts its own steps shows how long the walks are:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <set>
// A set's iterator that counts every step it moves, forwards or back.
long long steps = 0;
struct Counting {
using iterator_category = std::bidirectional_iterator_tag;
using value_type = int;
using difference_type = std::ptrdiff_t;
using pointer = const int*;
using reference = const int&;
std::set<int>::const_iterator it;
reference operator*() const { return *it; }
Counting& operator++() { ++steps; ++it; return *this; }
Counting operator++(int) { Counting before = *this; ++*this; return before; }
Counting& operator--() { ++steps; --it; return *this; }
Counting operator--(int) { Counting before = *this; --*this; return before; }
bool operator==(const Counting& other) const { return it == other.it; }
};
// The same set of 100,000 even numbers and the same 500 queries as set_search.cpp.
int main() {
std::set<int> s;
for (int i = 0; i < 100'000; ++i) s.insert(2 * i);
Counting first{s.cbegin()}, last{s.cend()};
long long size = std::distance(first, last);
std::cout << "std::distance(first, last) = " << size << ", in " << steps << " steps\n";
steps = 0;
long long total = 0, most = 0;
int queries = 0;
for (int x = 1; x < 200'000; x += 400) {
long long before = steps;
total += *std::lower_bound(first, last, x);
most = std::max(most, steps - before);
++queries;
}
std::cout << queries << " calls of std::lower_bound, total " << total << ": " << steps / queries
<< " steps per call on average, " << most << " at most\n";
} from session import run
# The counting program, built and run with both compilers and their standard libraries.
run("""
clang++ -std=c++23 -O2 -Wall -Wextra count_steps.cpp -o count_steps && ./count_steps
g++-16 -std=c++23 -O2 -Wall -Wextra count_steps.cpp -o count_steps-gcc && ./count_steps-gcc
""") Output
$ clang++ -std=c++23 -O2 -Wall -Wextra count_steps.cpp -o count_steps && ./count_steps std::distance(first, last) = 100000, in 100000 steps 500 calls of std::lower_bound, total 49901000: 199995 steps per call on average, 200000 at most $ g++-16 -std=c++23 -O2 -Wall -Wextra count_steps.cpp -o count_steps-gcc && ./count_steps-gcc std::distance(first, last) = 100000, in 100000 steps 500 calls of std::lower_bound, total 49901000: 199995 steps per call on average, 200000 at most
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 steps_session.py
With both standard libraries, every call took about 200,000 steps on the set of 100,000. The first line shows where
half of them go: std::distance walks the whole range once to count it, and the halvings then walk about as far
again. So the 500 queries cost about 500 × 200,000 steps instead of about 500 × 17.
Every query of the program looks for an odd number, which the set of even numbers never holds. The chart shows how the two kinds of work grow for such a missing value as n doubles up to 100,000, the size of the program’s set: the walk grows in step with n, as a scan’s checks do, and the member function’s descent of the tree grows like binary search’s probes:
- Linear search, measured (circles)
- Binary search, measured (squares)
- Derived count (dashed): n for linear search; ⌊log₂ n⌋ + 1 for binary search
- The size in focus (ringed)
n = 1: linear search checks 1 value and binary search makes 1 probe. The dashed lines are the derived counts: n and ⌊log₂ n⌋ + 1.
From n = 1 to 100,000, searching for a value larger than every one, the counts grew: linear search from 1 to 100,000 values checked and binary search from 1 to 17 probes. Each matched the derived count at every size: n for linear search and ⌊log₂ n⌋ + 1 for binary search.
Every measured count as a table
| n | Linear search: values checked | Binary search: probes |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 4 | 4 | 3 |
| 8 | 8 | 4 |
| 16 | 16 | 5 |
| 32 | 32 | 6 |
| 64 | 64 | 7 |
| 128 | 128 | 8 |
| 256 | 256 | 9 |
| 512 | 512 | 10 |
| 1,024 | 1,024 | 11 |
| 2,048 | 2,048 | 12 |
| 4,096 | 4,096 | 13 |
| 8,192 | 8,192 | 14 |
| 16,384 | 16,384 | 15 |
| 32,768 | 32,768 | 16 |
| 65,536 | 65,536 | 17 |
| 100,000 | 100,000 | 17 |
At n = 100,000 the scan checks 100,000 values and binary search makes 17 probes. The walk of std::lower_bound took
twice the scan’s count, because it counts the range first, and it doubles with n in the same way, while the probes
gain only one each time n doubles.
Checkpoint
Check: A set's own lower_bound against std::lower_bound
Traps the compiler accepts
The next two programs compile cleanly with -Wall -Wextra. They are built here with -fsanitize=address,undefined,
which adds checks that report the mistake while the program runs:
C++ (traps.cpp) · traps.cpp
#include <cstddef>
#include <iostream>
#include <map>
#include <numeric>
#include <string>
#include <vector>
int main() {
std::cout << std::unitbuf; // print each line at once, so it appears before any sanitizer report
// Reading a missing key with [] inserts it.
std::map<std::string, int> score;
if (score["asha"] == 0) std::cout << "asha has no score\n";
std::cout << "size after one lookup: " << score.size() << ", contains(\"ravi\"): " << score.contains("ravi")
<< ", size still " << score.size() << '\n';
// size() is unsigned: on an empty vector, size() - 1 wraps around to the largest size_t.
std::vector<int> empty;
std::cout << "empty.size() - 1 = " << empty.size() - 1 << '\n';
// The type of accumulate's start value is the type of the sum.
std::vector<int> big = {2'000'000'000, 2'000'000'000, 2'000'000'000};
long long wide = std::accumulate(big.begin(), big.end(), 0LL);
std::cout << "accumulate from 0LL: " << wide << '\n';
int narrow = std::accumulate(big.begin(), big.end(), 0);
std::cout << "accumulate from 0: " << narrow << '\n';
// (lo + hi) / 2 overflows for large ends; std::midpoint (C++20) and lo + (hi - lo) / 2 do not.
int lo = 2'000'000'000, hi = 2'100'000'000;
std::cout << "midpoint " << std::midpoint(lo, hi) << ", lo + (hi - lo) / 2 = " << lo + (hi - lo) / 2 << '\n';
int naive = (lo + hi) / 2;
std::cout << "(lo + hi) / 2 = " << naive << '\n';
} C++ (oob.cpp) · oob.cpp
#include <cstddef>
#include <iostream>
#include <vector>
// The sum of the steps between neighbours. The loop bound is wrong when v is empty: v.size() - 1 wraps around.
long long sum_of_steps(const std::vector<int>& v) {
long long total = 0;
for (std::size_t i = 0; i < v.size() - 1; ++i) total += v[i + 1] - v[i];
return total;
}
int main() {
std::cout << std::unitbuf;
std::cout << sum_of_steps({3, 8, 6}) << '\n';
std::cout << sum_of_steps({5}) << '\n';
std::vector<int> none;
none.reserve(4); // room for 4 elements, none of them in use
std::cout << sum_of_steps(none) << '\n';
} from session import run
# Built with the address and undefined-behaviour sanitizers, which check the program while it runs.
run("""
clang++ -std=c++23 -g -Wall -Wextra -fsanitize=address,undefined traps.cpp -o traps && ./traps
clang++ -std=c++23 -g -Wall -Wextra -fsanitize=address,undefined oob.cpp -o oob && ./oob
""") Output
$ clang++ -std=c++23 -g -Wall -Wextra -fsanitize=address,undefined traps.cpp -o traps && ./traps
asha has no score
size after one lookup: 1, contains("ravi"): 0, size still 1
empty.size() - 1 = 18446744073709551615
accumulate from 0LL: 6000000000
accumulate.h:30:32: runtime error: signed integer overflow: 2000000000 + 2000000000 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior accumulate.h:30:32
accumulate from 0: 1705032704
midpoint 2050000000, lo + (hi - lo) / 2 = 2050000000
traps.cpp:31:21: runtime error: signed integer overflow: 2000000000 + 2100000000 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior traps.cpp:31:21
(lo + hi) / 2 = -97483648
$ clang++ -std=c++23 -g -Wall -Wextra -fsanitize=address,undefined oob.cpp -o oob && ./oob
3
0
SUMMARY: AddressSanitizer: container-overflow oob.cpp:8 in sum_of_steps(std::__1::vector<int, std::__1::allocator<int>> const&)
[exit status 134]
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 traps_session.py
m[key]inserts. Reading a missing key withoperator[]creates it with a default value, so the check for Asha’s score grew the map to size 1. Test membership withcontains(C++20) orfind, which change nothing.- Sizes are unsigned.
empty.size() - 1is not -1 but 18,446,744,073,709,551,615, the largestsize_t. Inoob.cppthe loopi < v.size() - 1therefore runs past the end of an empty vector; with room reserved but no elements in use, AddressSanitizer reported a container overflow at line 8 and stopped the program. Writei + 1 < v.size().
Step through those lines of the recorded run, one lookup and one comparison at a time:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- An empty map. traps.cpp starts with an empty std::map<std::string, int> named score. Its size is 0.
- The lookup inserts. score["asha"] asks for a key that is not there. operator[] does not fail: it inserts "asha" with the value 0 and returns that 0, so the test is true and the program prints "asha has no score".
- A lookup that only looks. contains("ravi") returns false and inserts nothing, so the program printed size still 1. find, which returns end() for a missing key, changes nothing either.
- The size wraps. size() returns std::size_t, an unsigned type. On the empty vector, 0 - 1 cannot be -1, so it wraps around to the largest size_t, 2 to the power 64 minus 1 on this 64-bit build: 18,446,744,073,709,551,615.
- The loop runs. oob.cpp sums the steps between neighbours with i < v.size() - 1. For none, with room for 4 but no element in use, the right side is that huge number, so i = 0 passes the test and the body reads v[i + 1] and v[i].
- The sanitizer stops it. AddressSanitizer knows where the vector's elements end inside its reserved room, so the first read past them stops the program with a container-overflow report at line 8, exit status 134. Writing i + 1 < v.size() makes the test false at once.
Checkpoint
Check: Lookups that insert and sizes that wrap
Signed overflow is undefined, and the sanitizer reports it
The same run holds two more traps, both sums that do not fit in an int:
std::accumulateadds in the type of its start value. With0, the sum of three values of 2 × 10⁹ is computed inint: the undefined-behaviour sanitizer reported a signed integer overflow insideaccumulate, and the program printed 1,705,032,704. With0LLit printed 6,000,000,000.- Signed overflow is undefined behaviour.
(lo + hi) / 2with ends near 2 × 10⁹ overflowed and printed a negative number.std::midpoint(C++20) andlo + (hi - lo) / 2give 2,050,000,000.
Follow the two running totals of accumulate, one from 0 and one from 0LL, through the three additions:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- Two start values. accumulate keeps its running total in the type of its start value. Called with 0, the total is an int, whose largest value is 2,147,483,647; called with 0LL, it is a long long.
- The first value. The first value, 2,000,000,000, fits in both types, so both totals are 2,000,000,000.
- The second value. The second addition needs 4,000,000,000. The long long holds it, but the int cannot: this is signed overflow, which is undefined behaviour, and the undefined-behaviour sanitizer reported it inside accumulate. This build went on with the low 32 bits, -294,967,296.
- The third value. The third addition brings the int total to 1,705,032,704, which fits again, so nothing more is reported. The long long reaches 6,000,000,000, the true sum.
- What was printed. The program printed 1,705,032,704 from 0 and 6,000,000,000 from 0LL. The int lost 2 to the power 32 on the way: 6,000,000,000 - 4,294,967,296 = 1,705,032,704, and storing the result in a long long afterwards cannot bring it back.
The negative midpoint comes from the same arithmetic. 2,000,000,000 + 2,100,000,000 is 4,100,000,000, which does not
fit in an int; this build kept its low 32 bits, 4,100,000,000 − 4,294,967,296 = −194,967,296, and halving that
printed −97,483,648.
Without the sanitizers, the first and last results are just wrong numbers, and an optimiser may even transform code
on the assumption that signed overflow never happens. Build practice code with the sanitizers on, and keep -O2
builds for timing.
Key idea
A C++ sum is computed in the type of its operands, and accumulate’s total in the type of its start value, so
choose a 64-bit type before the first addition: converting a wrong int afterwards cannot bring the lost bits back.
Checkpoint
Check: Signed overflow and the sanitizer that reports it
Two lines speed up cin with GCC’s library, not with Apple’s
C++ streams start synchronised with C’s standard input and output, and cin is
Tied to an output stream: before each of its input or output operations, a stream first calls flush() on the stream it is tied to. By default cin is tied to cout.
to cout, so every read first flushes the output. cppreference says that turning the synchronisation off “may be
considerably faster in some cases”. How much depends on the standard library, so the same reader was built with both:
C++ (read_ints.cpp) · read_ints.cpp
#include <chrono>
#include <cstring>
#include <iostream>
// Reads a count and then that many integers from standard input, and prints their sum and the time it took.
// With the argument "fast", the stream is first untied from C's stdio and from cout.
int main(int argc, char** argv) {
bool fast = argc > 1 && std::strcmp(argv[1], "fast") == 0;
auto start = std::chrono::steady_clock::now();
if (fast) {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
}
int n;
std::cin >> n;
long long sum = 0;
for (int i = 0; i < n; ++i) {
int x;
std::cin >> x;
sum += x;
}
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
std::cout << (fast ? "unsynced cin: " : "default cin: ") << "sum " << sum << ", " << ms << " ms\n";
} C++ (read_scanf.cpp) · read_scanf.cpp
#include <chrono>
#include <cstdio>
int main() {
auto start = std::chrono::steady_clock::now();
int n;
if (std::scanf("%d", &n) != 1) return 1;
long long sum = 0;
for (int i = 0; i < n; ++i) {
int x;
if (std::scanf("%d", &x) != 1) return 1;
sum += x;
}
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
std::printf("scanf: sum %lld, %lld ms\n", sum, static_cast<long long>(ms));
} import random
# 200,000 integers between -10^9 and 10^9, ten to a line, after their count: a typical large test input.
random.seed(1)
n = 200_000
values = [random.randint(-10**9, 10**9) for _ in range(n)]
with open("numbers.txt", "w") as f:
f.write(f"{n}\n")
for i in range(0, n, 10):
f.write(" ".join(map(str, values[i : i + 10])) + "\n")
print(f"wrote {n} numbers, sum {sum(values)}") from session import run
# The same reader built with GCC 16 (libstdc++) and with Apple clang (libc++), then C's scanf for comparison.
run("""
python3 make_numbers.py
g++-16 -std=c++23 -O2 read_ints.cpp -o read_gcc && ./read_gcc < numbers.txt && ./read_gcc fast < numbers.txt
clang++ -std=c++23 -O2 read_ints.cpp -o read_clang && ./read_clang < numbers.txt && ./read_clang fast < numbers.txt
clang++ -std=c++23 -O2 read_scanf.cpp -o read_scanf && ./read_scanf < numbers.txt
""") Output
$ python3 make_numbers.py wrote 200000 numbers, sum -213236582986 $ g++-16 -std=c++23 -O2 read_ints.cpp -o read_gcc && ./read_gcc < numbers.txt && ./read_gcc fast < numbers.txt default cin: sum -213236582986, 566 ms unsynced cin: sum -213236582986, 15 ms $ clang++ -std=c++23 -O2 read_ints.cpp -o read_clang && ./read_clang < numbers.txt && ./read_clang fast < numbers.txt default cin: sum -213236582986, 845 ms unsynced cin: sum -213236582986, 929 ms $ clang++ -std=c++23 -O2 read_scanf.cpp -o read_scanf && ./read_scanf < numbers.txt scanf: sum -213236582986, 29 ms
This output changes from run to run: the times depend on the computer and on what else it is running
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 io_session.py
With GCC’s libstdc++, the standard library of most judges, std::ios::sync_with_stdio(false) and cin.tie(nullptr)
made the same loop dozens of times faster. With Apple clang’s libc++ on macOS, both cin versions stayed slow, while
scanf was fast. So write the two lines at the top of main for a judge, and if you practise on a Mac, do not
judge a solution’s speed by its cin time there. After switching synchronisation off, do not mix cin with scanf,
or cout with printf, in one program. For output, end lines with '\n' rather than std::endl, which also flushes
the stream every time.
All five runs printed the same sum, so only the reading differs. Read the times in the session above as a ratio between two readers on the same computer, never as a speed that a judge will reproduce.
Checkpoint
Check: Fast input with each standard library
Your compiler’s library decides which C++23 features you get
Choosing -std=c++23 asks for the C++23 language, but the library features come from the compiler’s standard
library, and each library adds them at its own pace. feature-test macro: A macro such as __cpp_lib_ranges_enumerate that a C++ standard library defines when it provides a feature, so a program can test for the feature with #ifdef before it uses it. such as
__cpp_lib_ranges_enumerate tell a program what it got:
C++ (features.cpp) · features.cpp
#include <print>
#include <ranges>
#include <vector>
int main() {
std::vector<int> scores = {72, 100, 9};
std::vector<char> names = {'a', 'b', 'c'};
auto doubled = scores | std::views::transform([](int s) { return 2 * s; }) | std::ranges::to<std::vector>();
for (auto [name, score] : std::views::zip(names, doubled)) std::print("{}={} ", name, score);
std::println("");
#ifdef __cpp_lib_ranges_enumerate
for (auto [i, s] : std::views::enumerate(scores)) std::print("{}:{} ", i, s);
std::println("");
#else
std::println("views::enumerate: not in this standard library");
#endif
} C++ (enumerate.cpp) · enumerate.cpp
#include <print>
#include <ranges>
#include <vector>
int main() {
std::vector<int> scores = {72, 100, 9};
for (auto [i, s] : std::views::enumerate(scores)) std::print("{}:{} ", i, s);
std::println("");
} from session import run
# C++23 library features with each compiler's own standard library: libc++ (Apple clang) and libstdc++ (GCC 16).
run("""
clang++ -std=c++23 -Wall -Wextra features.cpp -o features && ./features
g++-16 -std=c++23 -Wall -Wextra features.cpp -o features-gcc && ./features-gcc
clang++ -std=c++23 enumerate.cpp -o enumerate
g++-16 -std=c++23 enumerate.cpp -o enumerate-gcc && ./enumerate-gcc
""") Output
$ clang++ -std=c++23 -Wall -Wextra features.cpp -o features && ./features
a=144 b=200 c=18
views::enumerate: not in this standard library
$ g++-16 -std=c++23 -Wall -Wextra features.cpp -o features-gcc && ./features-gcc
a=144 b=200 c=18
0:72 1:100 2:9
$ clang++ -std=c++23 enumerate.cpp -o enumerate
enumerate.cpp:7:36: error: no member named 'enumerate' in namespace 'std::ranges::views'
7 | for (auto [i, s] : std::views::enumerate(scores)) std::print("{}:{} ", i, s);
| ^~~~~~~~~
1 error generated.
[exit status 1]
$ g++-16 -std=c++23 enumerate.cpp -o enumerate-gcc && ./enumerate-gcc
0:72 1:100 2:9
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 features_session.py
Both libraries had std::print, std::ranges::to and views::zip. Apple clang’s libc++ did not have
views::enumerate, so the file that calls it failed to compile there, while GCC 16 compiled and ran it. Platforms add
another layer: HackerRank’s execution environment page offers “C++20” built with G++ 8.3.0 and “C++23” built with G++
14.2.0, and a compiler as old as G++ 8.3.0 predates most of the C++20 library, so on such a platform pick the option
with the newer compiler, whatever its label. When in doubt, a plain loop with an index is never missing.
The timeline shows the standard that added each feature used above, from the hash map of C++11 to the views of C++23:
- C++11
Hash maps, auto and the range-based for
std::unordered_map, the counter of the containers program, came with C++11, together with auto and the range-based for loop, which the containers and features programs use to walk their containers and views.
- C++17
Structured bindings
auto [dist, node] = frontier.top() names both members of a pair at once. The containers program unpacks every pair it reads this way.
- C++20
contains, midpoint, ranges and feature-test macros needed by traps.cpp
map::contains looks without inserting, std::midpoint averages without overflow and std::ranges::sort sorts a whole container. Feature-test macros became part of the standard, and the <version> header defines all of the library's; later standards add more, such as C++23's __cpp_lib_ranges_enumerate.
- C++23
print, ranges::to, zip and enumerate features.cpp
std::print and std::println format output, std::ranges::to collects a view into a container, views::zip walks ranges in step and views::enumerate pairs each element with its index. GCC's library added zip and enumerate in GCC 13.1 and print and ranges::to in 14.1; libc++'s status page lists enumerate as complete only in its version 23.
The timeline has 4 events, from C++11 to C++23.
Not affiliated
Based on public information about HackerRank. MySmartCoPilot is not affiliated with HackerRank, and HackerRank’s real environments may differ from what this lesson describes.
Checkpoint
Check: Which C++23 features a compiler has
Practise: predict what C++ does
Practise all six ideas of the lesson here. The questions follow your answers, the weakest idea first, and every choice gives its reason as soon as you pick it:
Practice that adapts to you
Practise this lesson
15 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Fresher · Why is std::priority_queue<int> a max-heap, and how do you make a min-heap?
std::priority_queue takes a comparison object, std::less<T> by default, and keeps the element that compares
greatest under it at the top, so with less the largest value is top(). That is the opposite of Python’s heapq,
Java’s PriorityQueue and Go’s container/heap, which put the smallest first. For a min-heap, pass the container and
std::greater<> as template arguments: std::priority_queue<int, std::vector<int>, std::greater<>>. For pairs such as
(distance, node) the same works, because pairs compare by their first member and then the second. Negating values
also works but is easy to forget when reading the top, and it fails for the smallest int, whose negation overflows.
Interviewers tend to push on this answer. Work through three likely follow-ups; every option tells you what it gets right or where it falls short:
Checkpoint
Interview round: three follow-up questions
The module’s bank has two harder questions that start from this lesson’s traps:
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
A C++ solution adds up to 2 × 10^5 values of up to 10^9 with std::accumulate(v.begin(), v.end(), 0) and stores the result in a long long. It passes locally and fails hidden tests. Explain why, how you would find it quickly, and the fix.
-
Mid to senior
A solution keeps bookings in a std::set and answers 10^5 queries with std::lower_bound(s.begin(), s.end(), t). It is correct but exceeds the time limit, although the set has only 10^5 elements. Explain why, and fix it.
Key takeaways
priority_queueis a max-heap; usestd::greater<>for a min-heap of numbers or pairs.- On
setandmap, call the memberlower_bound:std::lower_boundon their iterators walks linearly. m[key]inserts; usecontainsorfindto look.- Sizes are unsigned,
accumulatesums in the type of its start value, and signed overflow is undefined: practise with-fsanitize=address,undefined. - Untie and unsync the streams for judges; GCC’s
cinbecame dozens of times faster here, Apple’s libc++ did not. - Check library features with your actual compiler, or with feature-test macros, before relying on them.
Terms in this lesson
- feature-test macro
- A macro such as __cpp_lib_ranges_enumerate that a C++ standard library defines when it provides a feature, so a program can test for the feature with #ifdef before it uses it.
- max-heap
- A binary tree kept in an array in which every parent is at least as large as its children, so the largest element is at the front: reading it costs O(1), and adding or removing an element O(log n).
Corrections
- The set-search section now gives the measured walk of std::lower_bound on a set, about twice n steps per call (it counts the range first), where it said at most n.
References
- std::priority_queue (cppreference.com)
- std::priority_queue: constructors (cppreference.com)
- std::priority_queue::pop (cppreference.com)
- std::make_heap (cppreference.com)
- std::sort_heap (cppreference.com)
- std::set::lower_bound (cppreference.com)
- std::lower_bound (complexity for iterators that are not random access) (cppreference.com)
- std::map::operator[] (cppreference.com)
- std::map::at (cppreference.com)
- std::map::contains (cppreference.com)
- std::unordered_map (cppreference.com)
- Structured binding declaration (cppreference.com)
- std::accumulate (cppreference.com)
- std::midpoint (cppreference.com)
- Arithmetic operators: overflows (cppreference.com)
- std::ios_base::sync_with_stdio (cppreference.com)
- std::basic_ios::tie (cppreference.com)
- Feature testing (since C++20) (cppreference.com)
- std::print (cppreference.com)
- UndefinedBehaviorSanitizer (The LLVM Project)
- AddressSanitizer (The LLVM Project)
- libc++ C++23 status (The LLVM Project)
- libstdc++ implementation status: C++ 2023 (GNU Project (GCC))
- Execution environment (HackerRank)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress