Learning pathOriginal reference
Lesson 10 of 12

Memory, limits, and many test cases

Count peak live storage and total work across cases before choosing an algorithm.

Count what is alive together

Auxiliary space counts working storage beyond the supplied input under a stated convention. A sum helper uses a counter and total: O(1) extra space. Storing its n input values is O(n) input storage. Creating an independent length-n copy adds O(n) auxiliary storage.

Repeated pair checks can use O(n²) time while reusing a few counters and needing O(1) auxiliary space. Twenty sequential temporary copies do not imply twenty copies exist together. If those copies are kept, the peak storage changes.

Capacity and bytes matter too

int a[1000]{} allocates and initializes 1000 elements even if the active n is three. With capacity C, the allocation is O(C); a literal fixed capacity is constant with respect to active n. Describing a scalable array algorithm as O(n) storage assumes capacity grows with the needed size.

On a machine with four-byte int, one million elements occupy 4,000,000 bytes before overhead. A decimal MB is 10⁶ bytes; a MiB is 2²⁰ bytes. Actual type sizes and runtime overhead must fit the judge’s environment and memory limit.

Sum the cases the statement actually allows

Linear work on case sizes n₁ through nₜ gives O(t + Σnᵢ). If Σnᵢ ≤ 200000, do not assign 200000 elements independently to every case. Use local state inside solve() so each call starts fresh and old counts do not leak.

Quadratic work gives Σnᵢ², which can be as large as S² when total size is S. If each case also satisfies nᵢ ≤ B, then Σnᵢ² ≤ BS. Resetting a capacity-C array every case adds O(tC), even for mostly empty cases.

Use the maximum size as a plausibility check

At n = 100000, n² is ten billion while n⌈log₂ n⌉ is about 1.7 million. Those are growth-term estimates, not exact processor instructions. Hardware, operation costs, allocation, input/output, and compiler settings all affect elapsed time.

Prefer reducing obviously excessive work before benchmarking. A formula such as n(n + 1)/2 can replace a linear summation loop under a safe numeric bound, but a fast expression with an overflowing intermediate is still incorrect.

Growth explorer

Idealized operation counts show growth. Actual runtime also depends on the implementation and machine.

O(1)1
O(log n)7
O(n)100
O(n log n)665
O(n²)10,000

Bar lengths use a logarithmic scale. Logarithms use base 2.

Guided simulation · Change the inputs to test your understanding.

Pause & predict

At most 1000 cases have a combined length of at most 200000. Each case is scanned once. What best describes total work?

Choose an answer
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();
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

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.