Make the knowledge yours

Predict, write, and test. Open hints only after your own attempt.

72 practice prompts · Use your C++23 compiler to write and run solutions.

Level 0 Training · Session 1: Programming foundationsFrom a problem to a programRead the length and width of a rectangle, both from 1 to 1000. Print its area and perimeter, separated by a space. For 5 3, the output is 15 16.
Try it yourself

Turn the idea into code

Read the length and width of a rectangle, both from 1 to 1000. Print its area and perimeter, separated by a space. For 5 3, the output is 15 16.

Give me a hint

Write two formulas: area = length × width; perimeter = 2 × (length + width).

Show the explained solution

Read both dimensions, calculate each expression, and print the two results with an explicit separator. Parentheses ensure that both dimensions are doubled for the perimeter.

C++23
#include <iostream>

int main() {
    long long length = 0, width = 0;
    std::cin >> length >> width;
    std::cout << length * width << ' ' << 2 * (length + width) << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsVariables, types, and remembered valuesTwo inputs can each be as large as 1,000,000,000. Choose types and print their sum and product. Explain why choosing only from the individual inputs would be misleading.
Try it yourself

Turn the idea into code

Two inputs can each be as large as 1,000,000,000. Choose types and print their sum and product. Explain why choosing only from the individual inputs would be misleading.

Give me a hint

The product can reach 10¹⁸. Make the multiplication itself use long long.

Show the explained solution

Read both values into long long. Their product is then computed with the wider type, and the maximum allowed product fits a signed 64-bit integer.

C++23
#include <iostream>

int main() {
    long long a = 0, b = 0;
    std::cin >> a >> b;
    std::cout << a + b << ' ' << a * b << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsArithmetic without surprisesRead a duration from 0 to 10⁹ seconds. Print complete hours, remaining complete minutes, and remaining seconds. For 3671, print 1 1 11.
Try it yourself

Turn the idea into code

Read a duration from 0 to 10⁹ seconds. Print complete hours, remaining complete minutes, and remaining seconds. For 3671, print 1 1 11.

Give me a hint

Take a quotient for complete units and a remainder for what is left. A duration of 86400 seconds has 24 hours.

Show the explained solution

Divide by 3600 for hours. Split the remainder by 60 into minutes and seconds. Check that 3600 × hours + 60 × minutes + seconds reconstructs the input.

C++23
#include <iostream>

int main() {
    long long total = 0;
    std::cin >> total;
    long long hours = total / 3600;
    long long remaining = total % 3600;
    std::cout << hours << ' ' << remaining / 60 << ' ' << remaining % 60 << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsConditions and logical decisionsRead positive side lengths a, b, c ≤ 10⁹. Print INVALID, EQUILATERAL, ISOSCELES, or SCALENE for a nondegenerate triangle.
Try it yourself

Turn the idea into code

Read positive side lengths a, b, c ≤ 10⁹. Print INVALID, EQUILATERAL, ISOSCELES, or SCALENE for a nondegenerate triangle.

Give me a hint

First require all three pairwise sums to exceed the remaining side. Then test all-equal before any-equal.

Show the explained solution

Validity must come before classification. Equality in a triangle inequality is a flattened shape. Among valid triangles, all equal comes first because it also satisfies “some pair is equal.”

C++23
#include <iostream>

int main() {
    long long a = 0, b = 0, c = 0;
    std::cin >> a >> b >> c;
    if (!(a + b > c && a + c > b && b + c > a)) {
        std::cout << "INVALID\n";
    } else if (a == b && b == c) {
        std::cout << "EQUILATERAL\n";
    } else if (a == b || a == c || b == c) {
        std::cout << "ISOSCELES\n";
    } else {
        std::cout << "SCALENE\n";
    }
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsOptional: other ways to chooseRead a, an operator, and b, in that order. Support +, -, *, and integer /. Assume |a|, |b| ≤ 10⁶. Print ERROR for division by zero.
Try it yourself

Turn the idea into code

Read a, an operator, and b, in that order. Support +, -, *, and integer /. Assume |a|, |b| ≤ 10⁶. Print ERROR for division by zero.

Give me a hint

Use a char for the operator and long long for arithmetic. Guard the division within its branch.

Show the explained solution

Each case computes one operation and breaks. The divisor check is only needed for division. The task guarantees one of the four operators.

C++23
#include <iostream>

int main() {
    long long a = 0, b = 0;
    char operation = ' ';
    std::cin >> a >> operation >> b;
    switch (operation) {
        case '+': std::cout << a + b << '\n'; break;
        case '-': std::cout << a - b << '\n'; break;
        case '*': std::cout << a * b << '\n'; break;
        case '/':
            if (b == 0) { std::cout << "ERROR\n"; }
            else { std::cout << a / b << '\n'; }
            break;
    }
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsFor loops: make repetition preciseFor 0 ≤ n ≤ 10⁶, print the sum of the positive even integers no greater than n. For n = 7, print 12.
Try it yourself

Turn the idea into code

For 0 ≤ n ≤ 10⁶, print the sum of the positive even integers no greater than n. For n = 7, print 12.

Give me a hint

Visit 2, 4, 6, … and use a long long total initialized before the loop.

Show the explained solution

Each iteration adds the next positive even value exactly once. For n < 2, no additions happen, so the answer remains zero.

C++23
#include <iostream>

int main() {
    int n = 0;
    std::cin >> n;
    long long sum = 0;
    for (int i = 2; i <= n; i += 2) {
        sum += i;
    }
    std::cout << sum << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsWhile, do-while, and stopping rulesFor a stream of integers ending in 0, count the positive values before the sentinel. At most 100000 data values are given. For -3 5 9 -1 0, print 2.
Try it yourself

Turn the idea into code

For a stream of integers ending in 0, count the positive values before the sentinel. At most 100000 data values are given. For -3 5 9 -1 0, print 2.

Give me a hint

A count adds one per match. Read the next value even when the current value is not positive.

Show the explained solution

Keep the input update outside the positivity condition so every iteration advances. The initial sentinel produces a count of zero.

C++23
#include <iostream>

int main() {
    int x = 0, positive = 0;
    std::cin >> x;
    while (x != 0) {
        if (x > 0) { ++positive; }
        std::cin >> x;
    }
    std::cout << positive << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsBreak, continue, and early answersOptional: implement the primality test for 0 ≤ n ≤ 1000. Test 0, 1, 2, 9, and 17.
Try it yourself

Turn the idea into code

Optional: implement the primality test for 0 ≤ n ≤ 1000. Test 0, 1, 2, 9, and 17.

Give me a hint

The starting flag handles values below 2. A matching divisor makes further checks unnecessary.

Show the explained solution

The outputs for the five suggested inputs are NO, NO, YES, NO, YES. For eligible n, the loop examines every possible divisor other than 1 and n until it finds a counterexample.

C++23
#include <iostream>

int main() {
    int n = 0;
    std::cin >> n;
    bool prime = (n >= 2);
    for (int divisor = 2; divisor < n; ++divisor) {
        if (n % divisor == 0) {
            prime = false;
            break;
        }
    }
    std::cout << (prime ? "YES" : "NO") << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsFive patterns worth understandingRead 1 ≤ n ≤ 100000 followed by n values in [−10⁹, 10⁹]. Print their maximum without storing the whole list.
Try it yourself

Turn the idea into code

Read 1 ≤ n ≤ 100000 followed by n values in [−10⁹, 10⁹]. Print their maximum without storing the whole list.

Give me a hint

The first read establishes the candidate. Exactly n − 1 reads remain.

Show the explained solution

After each read, best is the maximum of everything consumed. This uses one running candidate and works for equal values, all-negative values, and n = 1.

C++23
#include <iostream>

int main() {
    int n = 0;
    std::cin >> n;
    long long best = 0;
    std::cin >> best;
    for (int i = 1; i < n; ++i) {
        long long x = 0;
        std::cin >> x;
        if (x > best) { best = x; }
    }
    std::cout << best << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsNested loops: rows and columnsPrint a growing triangle for 1 ≤ n ≤ 20. For n = 3, output rows containing *, **, and ***.
Try it yourself

Turn the idea into code

Print a growing triangle for 1 ≤ n ≤ 20. For n = 3, output rows containing *, **, and ***.

Give me a hint

The inner loop’s bound is the current row number.

Show the explained solution

Row r prints exactly r stars. The outer loop visits every required row once, and the newline ends each row.

C++23
#include <iostream>

int main() {
    int n = 0;
    std::cin >> n;
    for (int row = 1; row <= n; ++row) {
        for (int column = 1; column <= row; ++column) {
            std::cout << '*';
        }
        std::cout << '\n';
    }
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsTake a number apart, one digit at a timeCount the decimal digits of 0 ≤ n ≤ 10¹⁸. Print 1 for zero and 4 for 5072.
Try it yourself

Turn the idea into code

Count the decimal digits of 0 ≤ n ≤ 10¹⁸. Print 1 for zero and 4 for 5072.

Give me a hint

Increment a counter each time you remove one digit. Ensure one iteration happens for zero.

Show the explained solution

A do-while handles zero without a separate branch. Each iteration removes exactly one digit and increments the count once.

C++23
#include <iostream>

int main() {
    long long n = 0;
    std::cin >> n;
    int count = 0;
    do {
        ++count;
        n /= 10;
    } while (n > 0);
    std::cout << count << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 1: Programming foundationsMultiple cases and a debugging mindsetA sum-from-1-to-n solution uses i < n, declares sum = 0 inside the loop, and prints sum inside the loop. Repair all three issues for 0 ≤ n ≤ 10⁶.
Try it yourself

Turn the idea into code

A sum-from-1-to-n solution uses i < n, declares sum = 0 inside the loop, and prints sum inside the loop. Repair all three issues for 0 ≤ n ≤ 10⁶.

Give me a hint

What must be remembered between iterations? Is n included? How many final answers are required?

Show the explained solution

Place the long long sum before the loop, use i <= n, and print once after the loop. For n = 0 the loop does no work and prints 0.

C++23
#include <iostream>

int main() {
    int n = 0;
    std::cin >> n;
    long long sum = 0;
    for (int i = 1; i <= n; ++i) {
        sum += i;
    }
    std::cout << sum << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsArrays: give every value a placeRead 0 ≤ n ≤ 1000 integers and print them in reverse input order. Preserve the stored array.
Try it yourself

Turn the idea into code

Read 0 ≤ n ≤ 1000 integers and print them in reverse input order. Preserve the stored array.

Give me a hint

Store first, then visit signed indices from n − 1 down to 0. An empty input starts at −1 and skips the loop.

Show the explained solution

The output traversal changes the visiting order without assigning to any cell. Use a signed counter so the stopping value −1 is representable.

C++23
#include <iostream>

int main() {
    int a[1000]{};
    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; ++i) { std::cin >> a[i]; }
    for (int i = n - 1; i >= 0; --i) {
        if (i < n - 1) { std::cout << ' '; }
        std::cout << a[i];
    }
    std::cout << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsScan, count, search, and compareRead 1 ≤ n ≤ 1000 values in [−10⁹, 10⁹]. Count those strictly above their final average. Include tests with all equal and negative values.
Try it yourself

Turn the idea into code

Read 1 ≤ n ≤ 1000 values in [−10⁹, 10⁹]. Count those strictly above their final average. Include tests with all equal and negative values.

Give me a hint

Avoid dividing: multiply the candidate by the positive n using wide arithmetic.

Show the explained solution

The first pass computes the total and stores the values. The second applies the equivalent exact comparison. For [−10, −4, −4], the average is −6 and the answer is 2.

C++23
#include <iostream>

int main() {
    int a[1000]{};
    int n = 0;
    std::cin >> n;
    long long sum = 0;
    for (int i = 0; i < n; ++i) {
        std::cin >> a[i];
        sum += a[i];
    }
    int count = 0;
    for (int i = 0; i < n; ++i) {
        if (1LL * a[i] * n > sum) { ++count; }
    }
    std::cout << count << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsChange a sequence without losing itCount strict rises: elements larger than their immediate predecessor. For [2, 2, 5, 1, 4], print 2. Allow 0 ≤ n ≤ 1000.
Try it yourself

Turn the idea into code

Count strict rises: elements larger than their immediate predecessor. For [2, 2, 5, 1, 4], print 2. Allow 0 ≤ n ≤ 1000.

Give me a hint

The first element has no predecessor. Start the scan at index 1.

Show the explained solution

Only 5 > 2 and 4 > 1 are rises. Equal neighbours do not count. Zero- and one-element lists naturally return zero.

C++23
#include <iostream>

int main() {
    int a[1000]{};
    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; ++i) { std::cin >> a[i]; }
    int rises = 0;
    for (int i = 1; i < n; ++i) {
        if (a[i] > a[i - 1]) { ++rises; }
    }
    std::cout << rises << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsMatrices: think in two coordinatesFor 1 ≤ n ≤ 30 and matrix values in [−10⁹, 10⁹], sum all distinct cells on either diagonal. For the 3 × 3 matrix containing 1 through 9 by rows, print 25.
Try it yourself

Turn the idea into code

For 1 ≤ n ≤ 30 and matrix values in [−10⁹, 10⁹], sum all distinct cells on either diagonal. For the 3 × 3 matrix containing 1 through 9 by rows, print 25.

Give me a hint

Use one if condition: r == c OR r + c == n − 1.

Show the explained solution

The shared centre enters one addition, because a single true condition performs one update. A long long safely holds the sum under these bounds.

C++23
#include <iostream>

int main() {
    int n = 0;
    std::cin >> n;
    int a[30][30]{};
    for (int r = 0; r < n; ++r) {
        for (int c = 0; c < n; ++c) { std::cin >> a[r][c]; }
    }
    long long sum = 0;
    for (int r = 0; r < n; ++r) {
        for (int c = 0; c < n; ++c) {
            if (r == c || r + c == n - 1) { sum += a[r][c]; }
        }
    }
    std::cout << sum << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsCharacters become stringsRead one non-whitespace ASCII character. If it is a digit, print its numeric value and twice that value. Otherwise print NOT A DIGIT.
Try it yourself

Turn the idea into code

Read one non-whitespace ASCII character. If it is a digit, print its numeric value and twice that value. Otherwise print NOT A DIGIT.

Give me a hint

Check the digit range before subtracting '0'.

Show the explained solution

The range check proves the conversion represents a decimal digit. Input 7 gives 7 14; input A gives NOT A DIGIT.

C++23
#include <iostream>

int main() {
    char c = ' ';
    std::cin >> c;
    if ('0' <= c && c <= '9') {
        int digit = c - '0';
        std::cout << digit << ' ' << digit * 2 << '\n';
    } else {
        std::cout << "NOT A DIGIT\n";
    }
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsRead the text the problem actually givesRead t cases. Each case gives 1 ≤ n ≤ 1000 integers. Print the maximum of each case. Test one case with maximum 90 followed by the single value −5.
Try it yourself

Turn the idea into code

Read t cases. Each case gives 1 ≤ n ≤ 1000 integers. Print the maximum of each case. Test one case with maximum 90 followed by the single value −5.

Give me a hint

Initialize the candidate from the first element of the current case, not from an earlier case.

Show the explained solution

The two suggested answers are 90 and −5. Each case’s fresh candidate and active length keep state independent.

C++23
#include <iostream>

int main() {
    int a[1000]{};
    int t = 0;
    std::cin >> t;
    for (int test = 0; test < t; ++test) {
        int n = 0;
        std::cin >> n;
        for (int i = 0; i < n; ++i) { std::cin >> a[i]; }
        int best = a[0];
        for (int i = 1; i < n; ++i) {
            if (a[i] > best) { best = a[i]; }
        }
        std::cout << best << '\n';
    }
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsScan text: count, filter, transformRead one lowercase ASCII word of length at most 100000. Remove the vowels a, e, i, o, u and print the remaining characters in order.
Try it yourself

Turn the idea into code

Read one lowercase ASCII word of length at most 100000. Remove the vowels a, e, i, o, u and print the remaining characters in order.

Give me a hint

Use a fresh result string. Append only when the complete vowel condition is false.

Show the explained solution

The source word remains unchanged during traversal, so no indices shift. A word containing only vowels produces an empty output line.

C++23
#include <iostream>
#include <string>

int main() {
    std::string s;
    std::cin >> s;
    std::string result;
    int n = static_cast<int>(s.size());
    for (int i = 0; i < n; ++i) {
        char c = s[i];
        bool vowel = c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
        if (!vowel) { result.push_back(c); }
    }
    std::cout << result << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsJoin, compare, and find textRead two nonempty lowercase ASCII words and print the lexicographically smaller one. If they match, print that word once.
Try it yourself

Turn the idea into code

Read two nonempty lowercase ASCII words and print the lexicographically smaller one. If they match, print that word once.

Give me a hint

Compare the strings directly, rather than comparing only their lengths.

Show the explained solution

Use a <= b to choose the first string when it is smaller or equal; otherwise print b. No sorting algorithm is necessary for this two-value decision.

C++23
#include <iostream>
#include <string>

int main() {
    std::string a, b;
    std::cin >> a >> b;
    if (a <= b) { std::cout << a << '\n'; }
    else { std::cout << b << '\n'; }
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsMirror pairs and common beginningsRead two full ASCII lines, each at most 100000 characters and possibly empty. Print their longest common prefix length, then the prefix itself on the next line.
Try it yourself

Turn the idea into code

Read two full ASCII lines, each at most 100000 characters and possibly empty. Print their longest common prefix length, then the prefix itself on the next line.

Give me a hint

Bounds first, equality second. Ordinary getline calls already consume each line ending.

Show the explained solution

The counter is the number of leading characters proven equal. Stop at a mismatch or either end. substr(0, length) then extracts exactly that common prefix.

C++23
#include <iostream>
#include <string>

int main() {
    std::string a, b;
    std::getline(std::cin, a);
    std::getline(std::cin, b);
    int n = static_cast<int>(a.size());
    int m = static_cast<int>(b.size());
    int length = 0;
    while (length < n && length < m && a[length] == b[length]) {
        ++length;
    }
    std::cout << length << '\n' << a.substr(0, length) << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsWord boundaries and reliable text testsReimplement word counting with the neighbour rule, without an insideWord flag. Empty lines are allowed; lines contain only ordinary spaces and other ASCII non-space characters.
Try it yourself

Turn the idea into code

Reimplement word counting with the neighbour rule, without an insideWord flag. Empty lines are allowed; lines contain only ordinary spaces and other ASCII non-space characters.

Give me a hint

A word begins at a non-space whose predecessor does not exist or is a space.

Show the explained solution

The i == 0 part must come first within the OR, so the previous-character access is skipped at the start. An empty or all-space line contributes no word starts.

C++23
#include <iostream>
#include <string>

int main() {
    std::string line;
    std::getline(std::cin, line);
    int words = 0;
    int n = static_cast<int>(line.size());
    for (int i = 0; i < n; ++i) {
        if (line[i] != ' ' && (i == 0 || line[i - 1] == ' ')) {
            ++words;
        }
    }
    std::cout << words << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsOptional: rearrange an active sequenceOptional: read 0 ≤ n ≤ 1000 integers and rotate the active array right by one. Leave an empty list empty.
Try it yourself

Turn the idea into code

Optional: read 0 ≤ n ≤ 1000 integers and rotate the active array right by one. Leave an empty list empty.

Give me a hint

Save the last value before shifting. Copy from right to left.

Show the explained solution

The saved value wraps into index zero, while every earlier element moves exactly one place right. The guard makes the empty case safe and a one-element list stays unchanged.

C++23
#include <iostream>

int main() {
    int a[1000]{};
    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; ++i) { std::cin >> a[i]; }
    if (n > 0) {
        int last = a[n - 1];
        for (int i = n - 1; i > 0; --i) { a[i] = a[i - 1]; }
        a[0] = last;
    }
    for (int i = 0; i < n; ++i) {
        if (i > 0) { std::cout << ' '; }
        std::cout << a[i];
    }
    std::cout << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 2: Arrays & stringsOptional: subsequences and useful toolsOptional: read a full ASCII line and replace every hyphen with a plus sign using a range-based loop. Explain why char c alone would not modify the string.
Try it yourself

Turn the idea into code

Optional: read a full ASCII line and replace every hyphen with a plus sign using a range-based loop. Explain why char c alone would not modify the string.

Give me a hint

Use a writable reference to each stored character.

Show the explained solution

char& c aliases the current character. Assigning through it changes the string; a plain char c would be only a copy.

C++23
#include <iostream>
#include <string>

int main() {
    std::string s;
    std::getline(std::cin, s);
    for (char& c : s) {
        if (c == '-') { c = '+'; }
    }
    std::cout << s << '\n';
    return 0;
}
Review the lesson
Level 0 Training · Session 3: Functions & complexityOne function, one clear jobWrite larger(a, b), then reuse it in maximumOfThree(a, b, c). Both helpers must return a result without printing. Inputs are integers from −10⁹ to 10⁹. Test −8, −2, −5 and equal values.
Try it yourself

Turn the idea into code

Write larger(a, b), then reuse it in maximumOfThree(a, b, c). Both helpers must return a result without printing. Inputs are integers from −10⁹ to 10⁹. Test −8, −2, −5 and equal values.

Give me a hint

Compare a with b first, then compare that result with c.

Show the explained solution

The largest of the first two values is the only candidate from that pair that can win the final comparison. This uses constant time and constant auxiliary space.

C++23
// Complete C++23 program. Input: three integers.
#include <iostream>
int larger(int a, int b) { return a > b ? a : b; }
int maximumOfThree(int a, int b, int c) {
    return larger(larger(a, b), c);
}
int main() {
    int a = 0, b = 0, c = 0;
    std::cin >> a >> b >> c;
    std::cout << maximumOfThree(a, b, c) << '\n';
}
Review the lesson
Level 0 Training · Session 3: Functions & complexityReturn, print, and start freshImplement clampToRange(value, low, high) for low ≤ high. Return the nearest endpoint for an outside value; otherwise return the original value. Test 17 3 10, both endpoints, and a negative interval.
Try it yourself

Turn the idea into code

Implement clampToRange(value, low, high) for low ≤ high. Return the nearest endpoint for an outside value; otherwise return the original value. Test 17 3 10, both endpoints, and a negative interval.

Give me a hint

Use two early returns for values outside the range; the remaining path is already inside.

Show the explained solution

The three cases cover all permitted inputs. Each performs a fixed number of comparisons, so the helper uses O(1) time and auxiliary space.

C++23
// Complete C++23 program. Input: value low high, with low <= high.
#include <iostream>
int clampToRange(int value, int low, int high) {
    if (value < low) return low;
    if (value > high) return high;
    return value;
}
int main() {
    int value = 0, low = 0, high = 0;
    std::cin >> value >> low >> high;
    std::cout << clampToRange(value, low, high) << '\n';
}
Review the lesson
Level 0 Training · Session 3: Functions & complexityCopies, references, and side effectsWrite orderPair(int& a, int& b) so the caller’s smaller value comes first. Test 9 2, equal values, and two negative values.
Try it yourself

Turn the idea into code

Write orderPair(int& a, int& b) so the caller’s smaller value comes first. Test 9 2, equal values, and two negative values.

Give me a hint

Swap only when a > b; preserve the old a in a temporary before assigning.

Show the explained solution

If a is already no greater than b, the contract is satisfied. Otherwise the swap reverses the two values without losing either one. The helper has O(1) time and auxiliary space.

C++23
// Complete C++23 program. Input: two integers.
#include <iostream>
void orderPair(int& a, int& b) {
    if (a > b) {
        int temporary = a;
        a = b;
        b = temporary;
    }
}
int main() {
    int a = 0, b = 0;
    std::cin >> a >> b;
    orderPair(a, b);
    std::cout << a << ' ' << b << '\n';
}
Review the lesson
Level 0 Training · Session 3: Functions & complexityArray helpers need a contractReturn the first zero-based index of the minimum in a nonempty array. Input: 1 ≤ n ≤ 1000, then n integers in [−10⁹, 10⁹]. For 7 −2 −2 9, return 1.
Try it yourself

Turn the idea into code

Return the first zero-based index of the minimum in a nonempty array. Input: 1 ≤ n ≤ 1000, then n integers in [−10⁹, 10⁹]. For 7 −2 −2 9, return 1.

Give me a hint

Keep a best index, initialized from a real element. Replace it only when a strictly smaller value appears.

Show the explained solution

After each visited index, best points to the earliest minimum of that prefix. Strict comparison preserves the earlier index on equality. The helper is O(n) time and O(1) auxiliary space.

C++23
// Complete C++23 program. Input: n, then n integers; 1 <= n <= 1000.
#include <iostream>
int indexOfMinimum(const int a[], int n) {
    int best = 0;
    for (int i = 1; i < n; ++i) {
        if (a[i] < a[best]) best = i;
    }
    return best;
}
int main() {
    int a[1000]{};
    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; ++i) std::cin >> a[i];
    std::cout << indexOfMinimum(a, n) << '\n';
}
Review the lesson
Level 0 Training · Session 3: Functions & complexityStrings and small helper teamsWrite a reusable palindrome helper for an ASCII line of length at most 100000. Count spaces and punctuation, preserve case, and treat the empty line as a palindrome. Do not build a reversed copy.
Try it yourself

Turn the idea into code

Write a reusable palindrome helper for an ASCII line of length at most 100000. Count spaces and punctuation, preserve case, and treat the empty line as a palindrome. Do not build a reversed copy.

Give me a hint

Compare the leftmost and rightmost remaining characters. A single mismatch is enough to reject.

Show the explained solution

After every successful comparison, the already-checked outside characters match. When the indices meet or cross, no unchecked pair remains. Each step removes two candidates, giving O(L) time and O(1) auxiliary space.

C++23
// Complete C++23 program. Input: one ASCII line, length <= 100000.
#include <iostream>
#include <string>
bool isPalindrome(const std::string& text) {
    int left = 0;
    int right = static_cast<int>(text.size()) - 1;
    while (left < right) {
        if (text[left] != text[right]) return false;
        ++left;
        --right;
    }
    return true;
}
int main() {
    std::string text;
    std::getline(std::cin, text);
    std::cout << (isPalindrome(text) ? "YES\n" : "NO\n");
}
Review the lesson
Level 0 Training · Session 3: Functions & complexityDescribe growth with Big-OFor 0 ≤ n ≤ 10⁶, count the body visits in for (int i = 0; i < n; i += 3). Give an exact count, a tight growth bound, and auxiliary space. Check n = 0, 1, and 8.
Try it yourself

Turn the idea into code

For 0 ≤ n ≤ 10⁶, count the body visits in for (int i = 0; i < n; i += 3). Give an exact count, a tight growth bound, and auxiliary space. Check n = 0, 1, and 8.

Give me a hint

List 0, 3, 6, … below n. A partial final group still contributes one visit.

Show the explained solution

The exact count is ceil(n/3), or (n + 2) / 3 under these bounds: 0, 1, and 3 for the requested cases. Including setup, time is Θ(n + 1); conventional positive-size shorthand is Θ(n). The counter and index use O(1) auxiliary space.

Review the lesson
Level 0 Training · Session 3: Functions & complexityLook past the number of loopsAn outer loop uses widths 1, 2, 4, … up to n. For each width, an inner loop makes exactly width visits. Find the visits for n = 10 and justify the general growth. Assume 1 ≤ n ≤ 10⁶ and a long long width.
Try it yourself

Turn the idea into code

An outer loop uses widths 1, 2, 4, … up to n. For each width, an inner loop makes exactly width visits. Find the visits for n = 10 and justify the general growth. Assume 1 ≤ n ≤ 10⁶ and a long long width.

Give me a hint

The widths below 10 are 1, 2, 4, and 8. Add them rather than multiplying the number of widths by 10.

Show the explained solution

The count is 1 + 2 + 4 + 8 = 15. For any n ≥ 1, the geometric sum is less than 2n and at least a constant fraction of n, so the total is Θ(n), with O(1) auxiliary space.

Review the lesson
Level 0 Training · Session 3: Functions & complexityHalving and square-root workWrite isPrime(int value) for −10⁹ ≤ value ≤ 10⁹. Return a bool and let main print YES or NO. Include tests −7, 0, 1, 2, 9, 49, and 97.
Try it yourself

Turn the idea into code

Write isPrime(int value) for −10⁹ ≤ value ≤ 10⁹. Return a bool and let main print YES or NO. Include tests −7, 0, 1, 2, 9, 49, and 97.

Give me a hint

Reject values below two. Return false on a divisor; place the final true after the loop.

Show the explained solution

Every composite positive value has a tested divisor at or below its square root. A divisor is sufficient evidence to reject; no divisor in the required range proves primality for values at least two.

C++23
// Complete C++23 program. Input: -10^9 <= value <= 10^9.
#include <iostream>
bool isPrime(int value) {
    if (value < 2) return false;
    for (int divisor = 2; divisor <= value / divisor; ++divisor) {
        if (value % divisor == 0) return false;
    }
    return true;
}
int main() {
    int value = 0;
    std::cin >> value;
    std::cout << (isPrime(value) ? "YES\n" : "NO\n");
}
Review the lesson
Level 0 Training · Session 3: Functions & complexityThe work hidden in a callFor q threshold queries on a stored n-element array, a read-only helper scans the whole array and counts values ≥ the threshold. Give total time and helper auxiliary space, including n = 0. Does using a const array parameter eliminate the repeated scans?
Try it yourself

Turn the idea into code

For q threshold queries on a stored n-element array, a read-only helper scans the whole array and counts values ≥ the threshold. Give total time and helper auxiliary space, including n = 0. Does using a const array parameter eliminate the repeated scans?

Give me a hint

Charge one full scan to each query, plus per-query setup and output.

Show the explained solution

The query batch takes O(q(n + 1)) time and O(1) helper auxiliary space. A const array parameter avoids mutation and does not copy all array elements, but the body still visits n values per query. The stored input itself uses separate storage.

Review the lesson
Level 0 Training · Session 3: Functions & complexityMemory, limits, and many test casesImplement solve() for one case: read 0 ≤ n ≤ 100000 scores in [0, 100], count scores ≥ 50, and print the count. main reads t and calls solve t times. The total score count is at most 100000. Avoid storing scores you never revisit.
Try it yourself

Turn the idea into code

Implement solve() for one case: read 0 ≤ n ≤ 100000 scores in [0, 100], count scores ≥ 50, and print the count. main reads t and calls solve t times. The total score count is at most 100000. Avoid storing scores you never revisit.

Give me a hint

Keep a local passed counter inside solve. Process each score as it arrives.

Show the explained solution

A local counter resets for each case. Streaming uses O(1) extra storage and O(t + Σnᵢ) total time. Test an empty case immediately after a case containing several passing scores.

C++23
// Complete C++23 program. Input: t, then n and n scores for each case.
#include <iostream>
bool isPassing(int score) { return score >= 50; }
void solve() {
    int n = 0, passed = 0;
    std::cin >> n;
    for (int i = 0; i < n; ++i) {
        int score = 0;
        std::cin >> score;
        if (isPassing(score)) ++passed;
    }
    std::cout << passed << '\n';
}
int main() {
    int t = 0;
    std::cin >> t;
    for (int test = 0; test < t; ++test) solve();
}
Review the lesson
Level 0 Training · Session 3: Functions & complexityOptional: more expressive interfacesRead 0 ≤ rows ≤ 100, then rows rows of exactly three integers in [−10⁹, 10⁹]. Write a read-only matrix helper and print the sum using a wide result.
Try it yourself

Turn the idea into code

Read 0 ≤ rows ≤ 100, then rows rows of exactly three integers in [−10⁹, 10⁹]. Write a read-only matrix helper and print the sum using a wide result.

Give me a hint

Share a constant column width between the caller’s array and the helper’s parameter. Use long long for the total.

Show the explained solution

The helper visits three cells per active row, so it has O(rows + 1) time and O(1) auxiliary space. The input wrapper allocates 100 × 3 integers regardless of the active row count.

C++23
// Complete C++23 program. Input: rows, then rows * 3 integers.
#include <iostream>
constexpr int COLUMNS = 3;
long long sumMatrix(const int a[][COLUMNS], int rows) {
    long long total = 0;
    for (int row = 0; row < rows; ++row) {
        for (int col = 0; col < COLUMNS; ++col) total += a[row][col];
    }
    return total;
}
int main() {
    int a[100][COLUMNS]{};
    int rows = 0;
    std::cin >> rows;
    for (int row = 0; row < rows; ++row) {
        for (int col = 0; col < COLUMNS; ++col) std::cin >> a[row][col];
    }
    std::cout << sumMatrix(a, rows) << '\n';
}
Review the lesson
Level 0 Training · Session 3: Functions & complexityOptional: recursion and pending workA helper prints n, recursively processes n − 1, then prints n again. It returns immediately for zero. Predict the output for n = 3 and implement it for 0 ≤ n ≤ 20.
Try it yourself

Turn the idea into code

A helper prints n, recursively processes n − 1, then prints n again. It returns immediately for zero. Predict the output for n = 3 and implement it for 0 ≤ n ≤ 20.

Give me a hint

Write a separate line for each unfinished call. The second print waits for the smaller call to return.

Show the explained solution

The output is 3, 2, 1, 1, 2, 3 on separate lines. There are n + 1 calls and 2n output lines, so time and ordinary call-stack space are O(n + 1). For zero, it prints no lines.

C++23
// Complete C++23 program. Input: 0 <= n <= 20.
#include <iostream>
void downAndUp(int n) {
    if (n == 0) return;
    std::cout << n << '\n';
    downAndUp(n - 1);
    std::cout << n << '\n';
}
int main() {
    int n = 0;
    std::cin >> n;
    downAndUp(n);
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsMeet your standard-library toolkitRead 0 ≤ n ≤ 200000 integers and keep only strictly positive values, preserving order and duplicates. Print the count, then the kept values. Print a blank second line when none survive.
Try it yourself

Turn the idea into code

Read 0 ≤ n ≤ 200000 integers and keep only strictly positive values, preserving order and duplicates. Print the count, then the kept values. Print a blank second line when none survive.

Give me a hint

Start with an empty vector. Append only when x > 0; zero is not positive.

Show the explained solution

After every input, the vector contains exactly the positive values seen so far in arrival order. The n input steps and amortized appends give O(n + 1) time and O(k + 1) stored elements, where k is the kept count.

C++23
// Complete C++23 program. Input: n, then n integers.
#include <iostream>
#include <vector>
int main() {
    int n = 0;
    std::cin >> n;
    std::vector<int> kept;
    for (int i = 0; i < n; ++i) {
        int x = 0;
        std::cin >> x;
        if (x > 0) kept.push_back(x);
    }
    std::cout << kept.size() << '\n';
    for (int i = 0; i < static_cast<int>(kept.size()); ++i) {
        if (i != 0) std::cout << ' ';
        std::cout << kept[i];
    }
    std::cout << '\n';
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsVector elements, size, and roomPredict each printed line: start empty; reserve(5); print size and whether capacity ≥ 5; resize(3, 8); push_back(2); print size and back; resize(2); print size and back; clear(); print empty and whether capacity ≥ 5.
Try it yourself

Turn the idea into code

Predict each printed line: start empty; reserve(5); print size and whether capacity ≥ 5; resize(3, 8); push_back(2); print size and back; resize(2); print size and back; clear(); print empty and whether capacity ≥ 5.

Give me a hint

Track the existing elements separately from allocated room. Check inequalities for capacity rather than a guessed exact value.

Show the explained solution

The lines are 0 1, 4 2, 2 8, and 1 1. Reserve creates no elements. Resize and push create 8 8 8 2; shrinking leaves 8 8. Clear removes those elements and retains capacity.

C++23
// Complete C++23 program. No input.
#include <iostream>
#include <vector>
int main() {
    std::vector<int> values;
    values.reserve(5);
    std::cout << values.size() << ' ' << (values.capacity() >= 5) << '\n';
    values.resize(3, 8);
    values.push_back(2);
    std::cout << values.size() << ' ' << values.back() << '\n';
    values.resize(2);
    std::cout << values.size() << ' ' << values.back() << '\n';
    values.clear();
    std::cout << values.empty() << ' ' << (values.capacity() >= 5) << '\n';
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsIterators, edits, and invalidationTrace a = 10 20 30 40 50 through reverse([1, 4)), insert 99 before index 2, then erase index 3. Give every intermediate sequence and explain which original value is erased.
Try it yourself

Turn the idea into code

Trace a = 10 20 30 40 50 through reverse([1, 4)), insert 99 before index 2, then erase index 3. Give every intermediate sequence and explain which original value is erased.

Give me a hint

Use the current indices after every operation, not the original ones.

Show the explained solution

After reversal: 10 40 30 20 50. After insertion: 10 40 99 30 20 50. After erasing current index 3: 10 40 99 20 50. The erased value is 30. The insertion changed where later values lived.

Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsAlgorithms over a rangeRead n, a target, and n integers. Remove every target value, print the number removed, then print the remaining distinct values in ascending order. Use C++23 library operations and handle an empty result.
Try it yourself

Turn the idea into code

Read n, a target, and n integers. Remove every target value, print the number removed, then print the remaining distinct values in ascending order. Use C++23 library operations and handle an empty result.

Give me a hint

std::erase removes target matches. Then sort, unique, and erase the tail after the returned iterator.

Show the explained solution

Removing matches is linear. Sorting groups duplicate values; unique keeps one in its logical prefix and the final erase changes the actual size. Overall time is O(1 + n log(n + 1)); stored input is O(n + 1), plus sorting implementation workspace.

C++23
// Complete C++23 program. Input: 0 <= n <= 200000, target, then n integers.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
    int n = 0, target = 0;
    std::cin >> n >> target;
    std::vector<int> values(n);
    for (int& x : values) std::cin >> x;
    std::cout << std::erase(values, target) << '\n';
    std::sort(values.begin(), values.end());
    auto newEnd = std::unique(values.begin(), values.end());
    values.erase(newEnd, values.end());
    for (int i = 0; i < static_cast<int>(values.size()); ++i) {
        if (i != 0) std::cout << ' ';
        std::cout << values[i];
    }
    std::cout << '\n';
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsVectors in functions and gridsRead positive rows and cols, each at most 300, then a matrix with values in [−10⁹, 10⁹]. Store it as a nested vector and print column sums from left to right.
Try it yourself

Turn the idea into code

Read positive rows and cols, each at most 300, then a matrix with values in [−10⁹, 10⁹]. Store it as a nested vector and print column sums from left to right.

Give me a hint

For each column, reset one long long total, then visit that column in every row.

Show the explained solution

The inner loop visits exactly the requested column. Repeating across all columns visits every cell once, giving O(rows × cols) processing time and stored cells. Wide totals handle sums exceeding int.

C++23
// Complete C++23 program. Input: rows cols, then the matrix row by row.
#include <iostream>
#include <vector>
int main() {
    int rows = 0, cols = 0;
    std::cin >> rows >> cols;
    std::vector<std::vector<int>> grid(rows, std::vector<int>(cols));
    for (auto& row : grid) {
        for (int& x : row) std::cin >> x;
    }
    for (int col = 0; col < cols; ++col) {
        long long total = 0;
        for (int row = 0; row < rows; ++row) total += grid[row][col];
        if (col != 0) std::cout << ' ';
        std::cout << total;
    }
    std::cout << '\n';
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsPairs and precise tie rulesFor a nonempty list of scores in [0, 100], return a pair containing the highest score and the one-based position of its first occurrence. Test 70 95 95 60 90.
Try it yourself

Turn the idea into code

For a nonempty list of scores in [0, 100], return a pair containing the highest score and the one-based position of its first occurrence. Test 70 95 95 60 90.

Give me a hint

Initialize from the first score. Update only when a strictly higher score appears.

Show the explained solution

The pair tracks the earliest best score in each processed prefix. Strict comparison keeps the first occurrence on ties. For the sample, the result is (95, 2); time is O(n), with O(1) helper auxiliary space.

C++23
// Complete C++23 program. Input: 1 <= n <= 200000, then n scores.
#include <iostream>
#include <utility>
#include <vector>
std::pair<int, int> firstHighest(const std::vector<int>& scores) {
    std::pair<int, int> answer{scores[0], 1};
    for (int i = 1; i < static_cast<int>(scores.size()); ++i) {
        if (scores[i] > answer.first) answer = {scores[i], i + 1};
    }
    return answer;
}
int main() {
    int n = 0;
    std::cin >> n;
    std::vector<int> scores(n);
    for (int& x : scores) std::cin >> x;
    auto answer = firstHighest(scores);
    std::cout << answer.first << ' ' << answer.second << '\n';
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsDeque: work at either endRead n, k, and n integers with 0 ≤ n, k ≤ 200000. Retain only the latest k arrivals without saving the full input elsewhere. Print them oldest retained first. Handle k = 0 and k > n.
Try it yourself

Turn the idea into code

Read n, k, and n integers with 0 ≤ n, k ≤ 200000. Retain only the latest k arrivals without saving the full input elsewhere. Print them oldest retained first. Handle k = 0 and k > n.

Give me a hint

Append at the back. If size is greater than k, discard the front.

Show the explained solution

The deque always represents the desired suffix of processed arrivals. If k exceeds n, nothing is discarded. If k is zero, all arrivals are immediately discarded and the output line is blank.

C++23
// Complete C++23 program. Input: n k, then n integers.
#include <deque>
#include <iostream>
int main() {
    int n = 0, k = 0;
    std::cin >> n >> k;
    std::deque<int> recent;
    for (int i = 0; i < n; ++i) {
        int x = 0;
        std::cin >> x;
        recent.push_back(x);
        if (static_cast<int>(recent.size()) > k) recent.pop_front();
    }
    for (int i = 0; i < static_cast<int>(recent.size()); ++i) {
        if (i != 0) std::cout << ' ';
        std::cout << recent[i];
    }
    std::cout << '\n';
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsQueue: serve the oldest firstImplement a service line. Commands: 1 id joins, 2 prints and removes the oldest ID, 3 prints it without removal. Print EMPTY for type 2 or 3 on an empty queue. There are at most 200000 valid commands.
Try it yourself

Turn the idea into code

Implement a service line. Commands: 1 id joins, 2 prints and removes the oldest ID, 3 prints it without removal. Print EMPTY for type 2 or 3 on an empty queue. There are at most 200000 valid commands.

Give me a hint

Handle insertion first, then guard all remaining accesses with empty(). Only type 2 removes.

Show the explained solution

The invariant is that the queue contains exactly the unserved arrivals in their original order. Each command uses O(1) queue operations, so total time is O(q + 1), with O(q + 1) possible stored items.

C++23
// Complete C++23 program. Input: q, then commands 1 id, 2, or 3.
#include <iostream>
#include <queue>
int main() {
    int q = 0;
    std::cin >> q;
    std::queue<int> waiting;
    while (q--) {
        int type = 0;
        std::cin >> type;
        if (type == 1) {
            int id = 0;
            std::cin >> id;
            waiting.push(id);
        } else if (waiting.empty()) {
            std::cout << "EMPTY\n";
        } else {
            std::cout << waiting.front() << '\n';
            if (type == 2) waiting.pop();
        }
    }
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsPriority queues: choose the next extremeRead n events as time ID, with nonnegative times and unique positive IDs. Print IDs in earlier-time order and smaller-ID order on ties. Use a min-priority queue of pairs; n may be zero.
Try it yourself

Turn the idea into code

Read n events as time ID, with nonnegative times and unique positive IDs. Print IDs in earlier-time order and smaller-ID order on ties. Use a min-priority queue of pairs; n may be zero.

Give me a hint

Store the fields as (time, ID), and use std::greater for that same pair type.

Show the explained solution

The minimum pair is exactly the earliest event with the required tie rule. Copy the top before popping. Individual pushes and all removals take O(1 + n log(n + 1)) total amortized time, with O(n + 1) storage.

C++23
// Complete C++23 program. Input: 0 <= n <= 200000, then time ID pairs.
#include <functional>
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
int main() {
    int n = 0;
    std::cin >> n;
    using Event = std::pair<int, int>;
    std::priority_queue<Event, std::vector<Event>, std::greater<Event>> events;
    for (int i = 0; i < n; ++i) {
        int time = 0, id = 0;
        std::cin >> time >> id;
        events.push({time, id});
    }
    while (!events.empty()) {
        Event next = events.top();
        events.pop();
        std::cout << next.second << '\n';
    }
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsStack: resolve the newest firstRead one line containing only (), [], and {}. Print YES if it is balanced, otherwise NO. The empty line is balanced. Test ([]), ([)], ((), and )(.
Try it yourself

Turn the idea into code

Read one line containing only (), [], and {}. Print YES if it is balanced, otherwise NO. The empty line is balanced. Test ([]), ([)], ((), and )(.

Give me a hint

Store unmatched openings. Every closing bracket must match the top, and the stack must be empty at the end.

Show the explained solution

After each accepted prefix, the stack is precisely its unmatched openings in order. Rejecting an empty or mismatched top detects invalid prefixes; final emptiness ensures every opening was closed.

C++23
// Complete C++23 program. Input: one bracket-only line, length <= 200000.
#include <iostream>
#include <stack>
#include <string>
bool matches(char open, char close) {
    return (open == '(' && close == ')') ||
           (open == '[' && close == ']') ||
           (open == '{' && close == '}');
}
bool balanced(const std::string& text) {
    std::stack<char> pending;
    for (char c : text) {
        if (c == '(' || c == '[' || c == '{') pending.push(c);
        else {
            if (pending.empty() || !matches(pending.top(), c)) return false;
            pending.pop();
        }
    }
    return pending.empty();
}
int main() {
    std::string text;
    std::getline(std::cin, text);
    std::cout << (balanced(text) ? "YES\n" : "NO\n");
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsCancellation, undo, and combined toolsProcess commands on total = 0: 1 x adds and remembers x, 2 undoes the most recent uncancelled addition if any, and 3 prints the total. Only type 3 prints. Allow up to 200000 commands with |x| ≤ 10⁹.
Try it yourself

Turn the idea into code

Process commands on total = 0: 1 x adds and remembers x, 2 undoes the most recent uncancelled addition if any, and 3 prints the total. Only type 3 prints. Allow up to 200000 commands with |x| ≤ 10⁹.

Give me a hint

Store each addition in a stack and maintain a long long total. Undo changes the total before popping its amount.

Show the explained solution

The stack holds exactly the actions still contributing to the total. Each action is pushed once and removed at most once, so the whole program is O(q + 1) time with O(q + 1) worst-case storage.

C++23
// Complete C++23 program. Input: q, then commands 1 x, 2, or 3.
#include <iostream>
#include <stack>
int main() {
    int q = 0;
    std::cin >> q;
    std::stack<long long> history;
    long long total = 0;
    while (q--) {
        int type = 0;
        std::cin >> type;
        if (type == 1) {
            long long amount = 0;
            std::cin >> amount;
            history.push(amount);
            total += amount;
        } else if (type == 2) {
            if (!history.empty()) {
                total -= history.top();
                history.pop();
            }
        } else {
            std::cout << total << '\n';
        }
    }
}
Review the lesson
Level 0 Training · Session 4: STL: sequences & adaptorsOptional: keep only the best kRead n, k, then n integers with 1 ≤ k ≤ n ≤ 200000. Print the kth largest occurrence, counting duplicates, while using O(k) logical container storage. For 5 1 9 9 2 7 with k = 3, print 7.
Try it yourself

Turn the idea into code

Read n, k, then n integers with 1 ≤ k ≤ n ≤ 200000. Print the kth largest occurrence, counting duplicates, while using O(k) logical container storage. For 5 1 9 9 2 7 with k = 3, print 7.

Give me a hint

Maintain the largest k arrivals in a min-heap. At the end, its smallest retained value has exactly the required rank.

Show the explained solution

After each arrival, the invariant keeps the largest k occurrences seen so far. The final minimum of those retained values is the kth largest overall. The program does not store the whole input and costs O(n log(k + 1)) amortized time.

C++23
// Complete C++23 program. Input: n k, then n integers; 1 <= k <= n.
#include <functional>
#include <iostream>
#include <queue>
#include <vector>
int main() {
    int n = 0, k = 0;
    std::cin >> n >> k;
    std::priority_queue<int, std::vector<int>, std::greater<int>> best;
    for (int i = 0; i < n; ++i) {
        int x = 0;
        std::cin >> x;
        best.push(x);
        if (static_cast<int>(best.size()) > k) best.pop();
    }
    std::cout << best.top() << '\n';
}
Review the lesson
Level 0 Training · Session 5: Sets & mapsThink in keys, not positionsFor arrivals 7, 2, 7, 7, 4, write every NEW/OLD result and distinct count. Then explain why a set cannot report the total number of 7s.
Try it yourself

Turn the idea into code

For arrivals 7, 2, 7, 7, 4, write every NEW/OLD result and distinct count. Then explain why a set cannot report the total number of 7s.

Give me a hint

After each insertion, write only the distinct keys. The insertion flag changes only for a previously absent key.

Show the explained solution

The lines are NEW 1, NEW 2, OLD 2, OLD 2, NEW 3. The set state ends as {2, 4, 7}; repeated insertions have discarded multiplicity. Use a frequency map or multiset to preserve that information.

Review the lesson
Level 0 Training · Session 5: Sets & mapsWalk and erase safelyRemove every even key from {-2, 0, 3, 4, 7} using an iterator loop. Explain what to print if no keys remain.
Try it yourself

Turn the idea into code

Remove every even key from {-2, 0, 3, 4, 7} using an iterator loop. Explain what to print if no keys remain.

Give me a hint

Use the same two-branch loop, replacing the condition with *it % 2 == 0.

Show the explained solution

Erase -2, 0, and 4; the survivors are 3 and 7. After the loop, check empty() before accessing either extreme. If the container is empty, print the task’s explicit empty result instead of dereferencing an iterator.

Review the lesson
Level 0 Training · Session 5: Sets & mapsFind the nearest valid keyFind the greatest key ≤ each threshold 1, 5, 8, 20 in {2, 5, 9}. Then give the inclusive iterator range for keys from 3 through 8.
Try it yourself

Turn the idea into code

Find the greatest key ≤ each threshold 1, 5, 8, 20 in {2, 5, 9}. Then give the inclusive iterator range for keys from 3 through 8.

Give me a hint

Separate the boundary that is too large from the affordable predecessor.

Show the explained solution

The predecessor answers are NONE, 5, 5, 9. The value interval uses [lower_bound(3), upper_bound(8)); it visits only 5. The backward guard handles the first query, and a nonempty end() boundary handles the last.

Review the lesson
Level 0 Training · Session 5: Sets & mapsEvery copy countsA multiset has 100000 copies of 5. Explain why calling count(5) once for every stored copy can be far slower than O(n log n).
Try it yourself

Turn the idea into code

A multiset has 100000 copies of 5. Explain why calling count(5) once for every stored copy can be far slower than O(n log n).

Give me a hint

Count the matching entries visited by one count call, then count how many calls are made.

Show the explained solution

Each count may traverse all 100000 matching copies, and there are 100000 calls. That is O(n²) work. Store 5 → 100000 in a frequency map if the required operation is repeatedly reading the number of copies.

Review the lesson
Level 0 Training · Session 5: Sets & mapsOne key, one recordThe updates for one product are 10, 4, 7. Give the result for keeping the first price, latest price, and total amount, and identify an operation for each.
Try it yourself

Turn the idea into code

The updates for one product are 10, 4, 7. Give the result for keeping the first price, latest price, and total amount, and identify an operation for each.

Give me a hint

The declaration can stay the same; the repeated-key policy is expressed by the update.

Show the explained solution

First: 10 using insert or try_emplace. Latest: 7 using assignment or insert_or_assign. Total: 21 using +=. Query with find when absence is possible, so inspecting an unknown product does not add a record.

Review the lesson
Level 0 Training · Session 5: Sets & mapsCounts, ties, and groupsBuild the position groups for 4, 2, 4, 7, 2, 4. Explain the total number of position visits during output.
Try it yourself

Turn the idea into code

Build the position groups for 4, 2, 4, 7, 2, 4. Explain the total number of position visits during output.

Give me a hint

Every original position belongs to one group only.

Show the explained solution

2 → [2, 5], 4 → [1, 3, 6], 7 → [4]. The groups print in key order, while positions within each group retain input order. Output visits six positions, even though the loops are nested.

Review the lesson
Level 0 Training · Session 5: Sets & mapsHashing and exact-key queriesA frequency hash map contains 8 → 2, 2 → 2, 3 → 1. Query absent key 99 without changing the final distinct count. How would you print all records in sorted order?
Try it yourself

Turn the idea into code

A frequency hash map contains 8 → 2, 2 → 2, 3 → 1. Query absent key 99 without changing the final distinct count. How would you print all records in sorted order?

Give me a hint

Separate exact-key lookup from output ordering.

Show the explained solution

Use find(99); its end() result means output zero, and size() stays 3. For deterministic numeric order, copy entries into a vector of pairs and sort it, or build an ordered map originally. A direct hash traversal does not guarantee 2, 3, 8.

Review the lesson
Level 0 Training · Session 5: Sets & mapsAsk the past before adding the presentTrace target 10 for [5] and for [5, 1, 5, 8]. State exactly when the successful pair appears.
Try it yourself

Turn the idea into code

Trace target 10 for [5] and for [5, 1, 5, 8]. State exactly when the successful pair appears.

Give me a hint

Write the set of prior keys immediately before each lookup.

Show the explained solution

The one-value case finds no prior 5 and returns NO. In the longer input, the first 5 misses, 1 misses complement 9, and the second 5 finds the earlier 5. The algorithm returns YES while still reading the remaining 8.

Review the lesson
Level 0 Training · Session 5: Sets & mapsRanks with a GNU ordered setPredict every output of the complete program, then explain what find_by_order(3) means after duplicate insertion.
Try it yourself

Turn the idea into code

Predict every output of the complete program, then explain what find_by_order(3) means after duplicate insertion.

Give me a hint

List the distinct keys and their zero-based ranks first.

Show the explained solution

The output is 3, 1, 7, 1 on separate lines. The tree contains {2, 7, 9}; ranks are 0, 1, 2. Rank 3 is past the last key, so the comparison with end() is true.

Review the lesson
Level 0 Training · Session 5: Sets & mapsRanks change; identities do notA ranked distinct set starts as {5, 12, 20}. Insert 8, erase 5, then ask for rank 1 and the number of keys below 12. Explain why an earlier saved rank may be misleading.
Try it yourself

Turn the idea into code

A ranked distinct set starts as {5, 12, 20}. Insert 8, erase 5, then ask for rank 1 and the number of keys below 12. Explain why an earlier saved rank may be misleading.

Give me a hint

Rebuild the sorted state after every update.

Show the explained solution

The states are {5, 8, 12, 20}, then {8, 12, 20}. Rank 1 is now 12, and one key is below 12. An earlier rank can identify a different item after updates; retain the key when identity matters.

Review the lesson
Level 0 Training · Session 5: Sets & mapsOptional: combine and compare keysFor A = [2, 8, 2, 5] and B = [8, 8, 1, 2, 9], give the distinct intersection, union, and A minus B.
Try it yourself

Turn the idea into code

For A = [2, 8, 2, 5] and B = [8, 8, 1, 2, 9], give the distinct intersection, union, and A minus B.

Give me a hint

Write each distinct collection before performing the requested membership rule.

Show the explained solution

Intersection: {2, 8}. Union: {1, 2, 5, 8, 9}. A minus B: {5}. Each appears once because the requested results are sets of distinct values, not lists of physical occurrences.

Review the lesson
Level 0 Training · Session 5: Sets & mapsMake the state tell the truthA command parser always reads type and x, but command 3 has no x. Explain the bug and how the complete program avoids it.
Try it yourself

Turn the idea into code

A command parser always reads type and x, but command 3 has no x. Explain the bug and how the complete program avoids it.

Give me a hint

Input is a stream; consuming an extra integer steals part of the next command.

Show the explained solution

Reading x after command 3 consumes the next command type and misaligns all subsequent input. Handle type 3 immediately and continue; only commands 1 and 2 read an x. The operation contract controls both the container update and input parsing.

Review the lesson
Level 0 Training · Session 6: Static range queriesBuild once. Query many times.Build every padded prefix for [6, −4, 2]. Answer one-based [1, 3] and [2, 3], then translate [2, 3] into a zero-based half-open interval.
Try it yourself

Turn the idea into code

Build every padded prefix for [6, −4, 2]. Answer one-based [1, 3] and [2, 3], then translate [2, 3] into a zero-based half-open interval.

Give me a hint

There are four prefix lengths: 0, 1, 2, and 3.

Show the explained solution

P = [0, 6, 2, 4]. The full sum is 4 − 0 = 4. Positions [2, 3] sum to 4 − 6 = −2. They are zero-based indices [1, 3), so the same answer is P[3] − P[1].

Review the lesson
Level 0 Training · Session 6: Static range queriesSafe sums and honest complexityThree values are each 1000000000. What should the full-range answer be? List the types and boundaries you would test in a rangeSum helper.
Try it yourself

Turn the idea into code

Three values are each 1000000000. What should the full-range answer be? List the types and boundaries you would test in a rangeSum helper.

Give me a hint

Check where arithmetic happens, where it is stored, and what type the function returns.

Show the explained solution

The answer is 3000000000. Use long long summands, prefix entries, and return type, with a const-reference vector parameter. Test [1,1], [n,n], [1,n], an interior interval, all-negative input, and a sum above the 32-bit signed limit.

Review the lesson
Level 0 Training · Session 6: Static range queriesTransform the question into a sumFor [0, 2, −2, 0], is position 1 balanced? Also count the positive values in positions [1, 4].
Try it yourself

Turn the idea into code

For [0, 2, −2, 0], is position 1 balanced? Also count the positive values in positions [1, 4].

Give me a hint

Balance compares sums, not side lengths. Positivity is a separate 0/1 transformation.

Show the explained solution

Position 1 is balanced: its empty left side totals 0 and its right side totals 2 − 2 + 0 = 0. Only the value 2 is positive, so the whole-range positive count is 1.

Review the lesson
Level 0 Training · Session 6: Static range queriesCount values with direct indexingFor domain [−3, 3], give the allocated size and indices for −3, 0, 3. Explain why using abs(x) would be wrong.
Try it yourself

Turn the idea into code

For domain [−3, 3], give the allocated size and indices for −3, 0, 3. Explain why using abs(x) would be wrong.

Give me a hint

Use x − LOW with LOW = −3.

Show the explained solution

Allocate 7 entries. The values map to indices 0, 3, and 6. Taking absolute values would merge −3 and 3, even though the task counts them as different values.

Review the lesson
Level 0 Training · Session 6: Static range queriesLetters and equal pairsCount equal pairs in [3, 0, 3, 5, 3, 0]. Then decide whether aabcc and cbaca are anagrams.
Try it yourself

Turn the idea into code

Count equal pairs in [3, 0, 3, 5, 3, 0]. Then decide whether aabcc and cbaca are anagrams.

Give me a hint

For each value, either count earlier matches or use f(f − 1)/2. For words, compare all 26 counts.

Show the explained solution

Value 3 occurs three times and contributes 3 pairs; value 0 occurs twice and contributes 1. Total: 4. The words are anagrams: both have two as, one b, and two cs.

Review the lesson
Level 0 Training · Session 6: Static range queriesWhich axis are you prefixing?In abacaba, count a in positions [2, 6], b in [1, 7], and a in [4, 4]. Explain the zero-based character conversion.
Try it yourself

Turn the idea into code

In abacaba, count a in positions [2, 6], b in [1, 7], and a in [4, 4]. Explain the zero-based character conversion.

Give me a hint

Write positions 1 through 7 above the letters. A prefix row i consumes text[i − 1].

Show the explained solution

The answers are 2, 2, and 0. The a occurrences in [2,6] are positions 3 and 5; b occurs at 2 and 6; position 4 is c. Convert the one-based character position i to string index i − 1 only when reading the character.

Review the lesson
Level 0 Training · Session 6: Static range queriesAdd to a range with two markersStart with five zeros. Apply [2,4] += 3, [1,2] += −1, [4,5] += 2. Find both the six real-and-sentinel markers and the five final values.
Try it yourself

Turn the idea into code

Start with five zeros. Apply [2,4] += 3, [1,2] += −1, [4,5] += 2. Find both the six real-and-sentinel markers and the five final values.

Give me a hint

Add all boundary contributions first, then take one running sum.

Show the explained solution

Markers at indices 1..6 are [−1, 3, 1, 2, −3, −2]. The five final values are [−1, 2, 3, 5, 2]. Including the sentinel returns the running added amount to zero.

Review the lesson
Level 0 Training · Session 6: Static range queriesBuild a pipeline of summariesStart with [4, −2, 7, 0, 3]. Add 3 to [2,4] and −1 to [1,2]. Give the final array and its sums for [1,5], [2,4], and [1,1].
Try it yourself

Turn the idea into code

Start with [4, −2, 7, 0, 3]. Add 3 to [2,4] and −1 to [1,2]. Give the final array and its sums for [1,5], [2,4], and [1,1].

Give me a hint

Reconstruct added amounts first, then combine them with the original values before building prefixes.

Show the explained solution

Added amounts are [−1, 2, 3, 3, 0]. Final values are [3, 0, 10, 3, 3]. The queried sums are 19, 13, and 3. These answers assume both updates have already happened.

Review the lesson
Level 0 Training · Session 6: Static range queriesPrefix sums in two dimensionsFor rows [2,1,−1,3], [0,4,2,−2], [5,−3,1,2], find the sum of rows 2..3 and columns 2..4. Verify directly and with prefix corners.
Try it yourself

Turn the idea into code

For rows [2,1,−1,3], [0,4,2,−2], [5,−3,1,2], find the sum of rows 2..3 and columns 2..4. Verify directly and with prefix corners.

Give me a hint

The desired cells are six values. The four needed prefix totals are 14, 5, 7, and 2.

Show the explained solution

Directly: 4 + 2 − 2 − 3 + 1 + 2 = 4. Inclusion-exclusion gives 14 − 5 − 7 + 2 = 4. Agreement verifies both the chosen rectangle and the corner formula.

Review the lesson
Level 0 Training · Session 6: Static range queriesOptional: different kinds of totalsFor [4, −2, 7, 0, 3], calculate the relative-weighted sum of [2,5]. Also normalize the integer −1 modulo 5.
Try it yourself

Turn the idea into code

For [4, −2, 7, 0, 3], calculate the relative-weighted sum of [2,5]. Also normalize the integer −1 modulo 5.

Give me a hint

The first value in the queried range must have weight 1, not its global index.

Show the explained solution

The weighted answer is 1×(−2) + 2×7 + 3×0 + 4×3 = 24. The normalized residue of −1 modulo 5 is 4. A global weighted prefix needs the (l − 1) correction to produce these local weights.

Review the lesson
Level 0 Training · Session 6: Static range queriesOptional: sparse values and rectangle updatesIn a 2×3 zero grid, add 4 to rows 1..2, columns 1..2, then add −1 to row 2, columns 2..3. Write the final grid.
Try it yourself

Turn the idea into code

In a 2×3 zero grid, add 4 to rows 1..2, columns 1..2, then add −1 to row 2, columns 2..3. Write the final grid.

Give me a hint

The overlap at row 2, column 2 receives both additions.

Show the explained solution

The first row is [4, 4, 0] and the second is [4, 3, −1]. The four-corner method combines each update’s contribution and reconstructs exactly these cell values.

Review the lesson
Level 0 Training · Session 6: Static range queriesOptional challenge: find matching prefixesFor [1, 2, −1, 1, 2] and target 3, list all matching subarrays using one-based inclusive endpoints. Explain the role of seen[0] = 1.
Try it yourself

Turn the idea into code

For [1, 2, −1, 1, 2] and target 3, list all matching subarrays using one-based inclusive endpoints. Explain the role of seen[0] = 1.

Give me a hint

The padded prefixes are [0, 1, 3, 2, 3, 5]. For each right prefix, look for an earlier value three smaller.

Show the explained solution

The matching ranges are [1,2], [1,4], and [4,5]. The initial zero prefix supplies the left boundary before position 1 for the first two matches. Looking up before insertion keeps all counted subarrays nonempty.

Review the lesson
From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.