Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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.

  • Intermediate
  • 15 minutes
  • Examples run with Python 3.14.8, Pyodide 314.0.7, Clang 21.0.0 and GCC 16.2.0
  • By MySmartCoPilot
Free lesson, Pro answers: 15 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

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:

Heaps, a min-heap of pairs, ordered queries and counting C++ · containers.cpp
#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';
}
session.py: runs the commands of a session and prints what they printed Python · session.py
"""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}]")
Built and run with Clang and GCC Python · containers_session.py
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_queue is 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 is std::less, so top() is the largest element. Passing std::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::set and std::map keep keys sorted and answer ordered questions: lower_bound(12) is the first key not less than 12, and std::prev of it is the key just below. A std::map is 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_map counts 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::sort with 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:

Interactive · step through it make_heap, then one pop_heap after another, on the four scores Arrange the values as a max-heap, then swap the root, the largest, to the end of the array, again and again.
Heap as an array: 40 75 62 90.40756290array:400751622903
  • being compared or looked at
  • being moved or written
  • the key, pivot or target

Pseudo-code

  1. build a max-heap from a (bottom-up)
  2. for end from n − 1 down to 1:
  3. swap a[0] and a[end] (the largest goes to its final place)
  4. 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.

Comparisons 0
Swaps 0

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

  1. Question 1 of 2 std::priority_queue<int> largest is built from the scores 40, 75, 62 and 90. What does largest.top() return, and what does it return after one pop()?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 90, then 75

    top() reads the root of the heap, the largest value under std::less. pop() calls std::pop_heap, which swaps the root to the back and sifts the new root down, then drops the back, so 75 is on top next.

  2. Question 2 of 2 std::set<int> slots = {9, 11, 14}; What is *slots.lower_bound(11)?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 11

    lower_bound(x) returns the first key that is not less than x, so for a key that is present it returns that key itself. In the program, lower_bound(12) returned 14 and std::prev of it gave 11.

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.

500 queries on a set of 100,000 numbers, two ways C++ · set_search.cpp
#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); });
}
Built with -O2 and run Python · search_session.py
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:

The same 500 queries through an iterator that counts its steps C++ · count_steps.cpp
#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";
}
Built and run with Clang and GCC Python · steps_session.py
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:

Interactive · watch it grow A scan's checks and binary search's probes, as n doubles up to 100,000 n doubles at each step, from 1 up to 100,000. Each mark counts what the algorithm did at that size; the dashed line is the count worked out by reasoning, drawn in full from the start.
A scan's checks and binary search's probes, as n doubles up to 100,000: at n = 1, linear search checks 1 value, binary search makes 1 probe; dashed lines show the derived counts.Linear search · values checked (log scale) · dashed: nBinary search · probes · dashed: ⌊log₂ n⌋ + 1110010k100k051015201101001k10k100kn, the size of the input (log scale: n doubles at each step)n = 1
  • 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.

Size n 1
Linear search · values checked 1
Binary search · probes 1
Scan ÷ binary search 1×
Every measured count as a table
Measured at each size, searching for a value larger than every one
nLinear search: values checkedBinary search: probes
111
222
443
884
16165
32326
64647
1281288
2562569
51251210
1,0241,02411
2,0482,04812
4,0964,09613
8,1928,19214
16,38416,38415
32,76832,76816
65,53665,53617
100,000100,00017

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

  1. Question 1 of 2 bookings is a std::set<int>. Which call finds the first booking at or after t in O(log n)?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: bookings.lower_bound(t)

    Ordered containers have their own lower_bound, upper_bound and equal_range, which use the tree. The non-member algorithms make O(log n) comparisons on any iterator, but they can jump in one step only on random-access ones.

  2. Question 2 of 2 A query calls std::lower_bound(s.begin(), s.end(), x) on a std::set of 1,000,000 values. About how many iterator steps does it take?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: About 2,000,000, twice n

    std::lower_bound halves the range by count, but a set's iterator moves one element at a time, so each query pays steps in proportion to n: n to count the range, then about n more to reach the midpoints. The member s.lower_bound(x) descends the tree instead, through a number of nodes that grows like binary search's probes.

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:

Four quiet traps and a loop bound that wraps

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';
}
Both programs with the sanitizers, built with Clang Python · traps_session.py
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 with operator[] creates it with a default value, so the check for Asha’s score grew the map to size 1. Test membership with contains (C++20) or find, which change nothing.
  • Sizes are unsigned. empty.size() - 1 is not -1 but 18,446,744,073,709,551,615, the largest size_t. In oob.cpp the loop i < v.size() - 1 therefore 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. Write i + 1 < v.size().

Step through those lines of the recorded run, one lookup and one comparison at a time:

Interactive · stage by stage A lookup that inserts, and a size that wraps Step through the recorded run. Watch the map's size after each lookup, then what size() - 1 becomes on an empty vector.
A lookup that inserts, and a size that wraps, step 6 of 6. Showing std::map score (size 1: {"asha", 0}), score["asha"] == 0, score.contains("ravi") (false; size still 1), empty.size() - 1 (18,446,744,073,709,551,615), i < v.size() - 1 (true for i = 0), AddressSanitizer (container-overflow, line 8). In focus: AddressSanitizer.std::map scoresize 1: {"asha", 0}score["asha"] == 0operator[] on a missing keyscore.contains("ravi")false; size still 1empty.size() - 118,446,744,073,709,551,615i < v.size() - 1true for i = 0AddressSanitizercontainer-overflow, line 8read past the end

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. An empty map. traps.cpp starts with an empty std::map<std::string, int> named score. Its size is 0.
  2. 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".
  3. 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.
  4. 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.
  5. 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].
  6. 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.

Number Base Converter See why size_t's largest value is 2 to the power 64, minus 1, in hexadecimal.

Checkpoint

Check: Lookups that insert and sizes that wrap

  1. Question 1 of 2 std::map<std::string, int> m; is empty. The code runs if (m["a"] == 0) {}, then m.contains("b"), then if (m["a"] > 0) {}. What is m.size() after that?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 1 keys

    The first m["a"] inserts "a" with the value 0. contains("b") only looks. The second m["a"] finds the key that is already there and inserts nothing, so the map holds one key.

  2. Question 2 of 2 Which loop over the neighbours of a vector v is safe when v is empty?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: for (std::size_t i = 0; i + 1 < v.size(); ++i)

    Subtracting from an unsigned size is the trap, so move the arithmetic to the other side: i + 1 < v.size() never goes below zero.

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::accumulate adds in the type of its start value. With 0, the sum of three values of 2 × 10⁹ is computed in int: the undefined-behaviour sanitizer reported a signed integer overflow inside accumulate, and the program printed 1,705,032,704. With 0LL it printed 6,000,000,000.
  • Signed overflow is undefined behaviour. (lo + hi) / 2 with ends near 2 × 10⁹ overflowed and printed a negative number. std::midpoint (C++20) and lo + (hi - lo) / 2 give 2,050,000,000.

Follow the two running totals of accumulate, one from 0 and one from 0LL, through the three additions:

Interactive · step by step Two running totals of the same three values Step through accumulate adding 2,000,000,000 three times. The left total is an int, from the start value 0; the right one is a long long, from 0LL.
Two running totals of the same three values, step 5 of 5. Showing start value 0, start value 0LL, + 2,000,000,000, + 2,000,000,000, + 2,000,000,000 (went on as -294,967,296), + 2,000,000,000, + 2,000,000,000, + 2,000,000,000. In focus: + 2,000,000,000, + 2,000,000,000.start value 0an int, up to 2,147,483,647start value 0LLa long long+ 2,000,000,0002,000,000,000+ 2,000,000,0002,000,000,000+ 2,000,000,000went on as -294,967,296+ 2,000,000,0004,000,000,000+ 2,000,000,0001,705,032,704+ 2,000,000,0006,000,000,000

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. 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.
  2. The first value. The first value, 2,000,000,000, fits in both types, so both totals are 2,000,000,000.
  3. 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.
  4. 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.
  5. 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

  1. Question 1 of 2 A std::vector<int> v holds three values of 2,000,000,000. Which line gives 6,000,000,000?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: long long s = std::accumulate(v.begin(), v.end(), 0LL);

    accumulate's total has the type of its start value. 0LL makes it a long long, which holds 6,000,000,000; 0 makes it an int, which cannot.

  2. Question 2 of 2 With int lo = 2000000000, hi = 2100000000; the expression (lo + hi) / 2 printed −97,483,648 in this build. What does lo + (hi - lo) / 2 give?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 2050000000

    hi - lo is 100,000,000, which fits easily, and half of it is 50,000,000, so the result is 2,050,000,000, the same as std::midpoint(lo, hi). Every intermediate value stays within the int range.

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:

Reading 200,000 integers with cin and with scanf

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));
}
make_numbers.py: the 200,000 integers every reader gets Python · make_numbers.py
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)}")
Each reader on the same 200,000 integers Python · io_session.py
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

  1. Question 1 of 2 What does std::cin.tie(nullptr) change?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: cin no longer flushes cout before each read

    By default cin is tied to cout, so each read first flushes cout. A judge does not need prompts to appear, so the flush is wasted work, and tie(nullptr) removes it.

  2. Question 2 of 2 After std::ios::sync_with_stdio(false), a program reads the count with scanf and the values with cin. What can go wrong?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: C and C++ input now buffer separately, so values can be read out of order or skipped

    Turning synchronisation off lets the C++ streams buffer on their own. After that, use cin alone for input and cout alone for output.

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:

ranges::to, views::zip, std::print and views::enumerate

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("");
}
The same files with libc++ and with libstdc++ Python · features_session.py
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:

Timeline · 4 events in order The C++ standards behind this lesson's programs Walk through the standards. Each adds what the programs above use; a compiler flag asks for the language, and the standard library decides how much of it you get.
  1. 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.

  2. 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.

  3. 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.

  4. 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

  1. Question 1 of 2 What does #ifdef __cpp_lib_ranges_enumerate in features.cpp test?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Whether the standard library in use provides views::enumerate

    Library feature-test macros are defined by the standard library when it provides a feature, so a program can use a feature where it exists and fall back where it does not.

  2. Question 2 of 2 A platform offers "C++20" built with G++ 8.3.0 and "C++23" built with G++ 14.2.0. Your solution uses views::zip and std::ranges::sort. Which do you choose?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The C++23 option with G++ 14.2.0

    Choose by the compiler version, then check its library's status page: GCC 14 has views::zip and std::ranges::sort, while G++ 8.3.0 predates most of the C++20 library.

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.

  1. Question 1 of 15 Which declaration gives a priority queue whose top() is the smallest int?

    Choose one answer.

    Show the answer: Question 1 of 15

    Answer: std::priority_queue<int, std::vector<int>, std::greater<>>

    The default comparison is std::less, which puts the largest element on top. std::greater<> as the third template argument reverses it; the second argument, the container, has to be named before it.

  2. Question 2 of 15 A min-heap of (distance, node) pairs, built with std::greater<>, receives {7, 'c'}, {2, 'a'} and {7, 'b'} in that order. In what order do they come out?

    Choose one answer.

    Show the answer: Question 2 of 15

    Answer: a2, then b7, then c7

    Pairs compare by their first member, then the second, so under std::greater<> the smallest pair is on top. The containers program printed a2 b7 c7.

  3. Question 3 of 15 A solution counts words in a std::unordered_map and must print them by count, highest first, then alphabetically. What do you do?

    Choose one answer.

    Show the answer: Question 3 of 15

    Answer: Copy the entries into a vector of pairs and sort it with a comparator on count, then word

    The containers program copies the counts into a vector and sorts with a comparator that compares the counts first and the words on a tie, which printed pear=3 fig=2 apple=1.

  4. Question 4 of 15 What does s.lower_bound(x) return for a std::set s?

    Choose one answer.

    Show the answer: Question 4 of 15

    Answer: An iterator to the first key not less than x, or end() when there is none

    lower_bound(x) answers "the first key at or after x". The key just below x is one step back from it.

  5. Question 5 of 15 A solution calls std::lower_bound(s.begin(), s.end(), x) on a std::set<int> of 10^5 elements for each of 10^5 queries. What is the cost?

    Choose one answer.

    Show the answer: Question 5 of 15

    Answer: About 2 × 10^10 iterator steps, because set iterators are not random access; s.lower_bound(x) is O(log n)

    The algorithm makes O(log n) comparisons but must move a bidirectional iterator step by step, which is linear per query: count_steps.cpp measured about 200,000 steps per call on a set of 100,000. The member function descends the tree directly; in the lesson's timed run its 500 queries took 0 ms, against close to a second for std::lower_bound.

  6. Question 6 of 15 Which of these look up a key in a std::map without ever inserting it?

    Choose every answer that is right.

    Show the answer: Question 6 of 15

    Answer:

    • m.contains(k)
    • m.find(k)
    • m.at(k)

    Only operator[] inserts. Use contains or find to test, and at() when a missing key is an error that should stop the program.

  7. Question 7 of 15 std::map<std::string, int> m; is empty. After if (m["x"] == 0) {}, what is m.size()?

    Choose one answer.

    Show the answer: Question 7 of 15

    Answer: 1

    operator[] inserts a value-initialised element when the key is missing, so the comparison itself added "x" with value 0. contains or find look without inserting; at() throws instead of inserting.

  8. Question 8 of 15 for (std::size_t i = 0; i < v.size() - 1; ++i) runs on an empty vector. What happens?

    Choose one answer.

    Show the answer: Question 8 of 15

    Answer: v.size() - 1 wraps to the largest size_t, so the loop reads past the end of the vector

    size() returns an unsigned type, so 0 - 1 is 18,446,744,073,709,551,615 and the condition is true. The lesson's run with AddressSanitizer stopped at the first read past the end. Write i + 1 < v.size() instead.

  9. Question 9 of 15 What does the C++ standard say about the result of a signed integer overflow?

    Choose one answer.

    Show the answer: Question 9 of 15

    Answer: It is undefined behaviour, so no result can be relied on and the compiler may assume it never happens

    Signed overflow is undefined behaviour. A build may wrap, as this one did, but another optimisation level or compiler may do something else, so the code must avoid the overflow.

  10. Question 10 of 15 Why does std::accumulate(v.begin(), v.end(), 0) overflow for three values of 2 × 10^9, even when its result is assigned to a long long?

    Choose one answer.

    Show the answer: Question 10 of 15

    Answer: The start value 0 is an int, so every partial sum is computed in int

    accumulate uses the type of its start value for the running total, and converting the final int to long long happens after the overflow. Pass 0LL so that the sum is a long long from the start.

  11. Question 11 of 15 A build like this one keeps the low 32 bits of a signed overflow. With lo = 1,500,000,000 and hi = 1,700,000,000 as ints, what would (lo + hi) / 2 print?

    Type a number.

    A hint

    lo + hi is 3,200,000,000; subtract 2 to the power 32, 4,294,967,296, then halve.

    Show the answer: Question 11 of 15

    Answer: -547483648

    3,200,000,000 does not fit in an int. Keeping the low 32 bits gives 3,200,000,000 − 4,294,967,296 = −1,094,967,296, and halving it gives −547,483,648. lo + (hi - lo) / 2 gives the right 1,600,000,000.

  12. Question 12 of 15 Why does a fast solution end its lines with '\n' rather than std::endl?

    Choose one answer.

    Show the answer: Question 12 of 15

    Answer: std::endl also flushes the stream every time

    std::endl writes a newline and flushes. '\n' only writes the newline and lets the stream's buffer collect the output, which is what a judge's large output needs.

  13. Question 13 of 15 Which statements about std::ios::sync_with_stdio(false); std::cin.tie(nullptr); are true?

    Choose every answer that is right.

    Show the answer: Question 13 of 15

    Answer:

    • It made cin dozens of times faster with GCC 16 in the lesson's run
    • After it, a program should not mix cin with scanf

    With libstdc++ the two lines cut the reading time by more than an order of magnitude; with libc++ both versions stayed slow and scanf was the fast one. Once the streams are no longer synchronised, C and C++ input buffer separately, so mixing them can read data out of order. The values read do not change.

  14. Question 14 of 15 What does the flag -std=c++23 decide?

    Choose one answer.

    Show the answer: Question 14 of 15

    Answer: The language level the compiler accepts; which library features exist still depends on its standard library

    The flag asks for the C++23 language. Library features such as views::enumerate come from the standard library, which is why the same flag gave different results with libc++ and libstdc++.

  15. Question 15 of 15 Built with Apple clang 21 and its libc++, what did features.cpp print on its second line?

    Choose one answer.

    Show the answer: Question 15 of 15

    Answer: views::enumerate: not in this standard library

    features.cpp uses the feature-test macro to choose a branch, so it builds with both libraries and says which one lacks the feature. enumerate.cpp calls views::enumerate directly and fails to compile with libc++.

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

  1. Question 1 of 3 Follow-up: "Dijkstra needs the smallest (distance, node) pair first. Declare the heap and say why it orders pairs correctly."

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: std::priority_queue<P, std::vector<P>, std::greater<>> with P = std::pair<int, int>; pairs compare by distance, then by node, so the smallest distance is always on top

    The containers program's frontier is this heap: it printed a2 b7 c7, the smallest distance first and equal distances ordered by node.

  2. Question 2 of 3 Follow-up: "What do push, top and pop cost?"

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: top() is O(1); push and pop are O(log n)

    cppreference describes priority_queue as constant time lookup of the largest element at the cost of logarithmic insertion and extraction; building it from a range with make_heap takes at most 3n comparisons.

  3. Question 3 of 3 Follow-up: "Why not push negated values into the default max-heap instead?"

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: It works for most ints, but every read of top() must negate back, and the smallest int has no positive counterpart, so negating it overflows

    -x for x = INT_MIN is signed overflow, undefined behaviour. std::greater<> reverses the order without touching the values.

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.

  1. 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.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. 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.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • priority_queue is a max-heap; use std::greater<> for a min-heap of numbers or pairs.
  • On set and map, call the member lower_bound: std::lower_bound on their iterators walks linearly.
  • m[key] inserts; use contains or find to look.
  • Sizes are unsigned, accumulate sums 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 cin became 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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.