Read the constraints before you write a line. A judge gets through roughly 10⁸ simple operations a second in C++, so the input size tells you which complexity you can afford. These are rules of thumb for planning, not guarantees.
At n = 2 × 10⁵ in C++ with 1 s, aim for O(n log n) or faster. Budget: about 10⁸ simple operations (the 10^8 rule itself).
| class | operations | size on a log scale, against the budget | time | verdict |
|---|---|---|---|---|
| O(1) | 1 | instant | fits easily | |
| O(log n) | 18 | instant | fits easily | |
| O(√n) | 447 | instant | fits easily | |
| O(n) | ≈ 2 × 10⁵ | 2 ms | fits easily | |
| O(n log n)← aim | ≈ 3.5 × 10⁶ | 35 ms | fits easily | |
| O(n²) | ≈ 4 × 10¹⁰ | 7 min | too slow | |
| O(n³) | ≈ 8 × 10¹⁵ | 3 years | too slow | |
| O(2ⁿ) | ≈ 10⁶⁰²⁰⁵ | longer than the universe has existed | too slow | |
| O(n!) | ≈ 10⁹⁷³³⁵⁰ | longer than the universe has existed | too slow |
Bars: operations on a log scale; the upright line is the budget. Fits easily: under a quarter of it · fits: under the budget · risky: up to 4× over, so constant factors decide · too slow: beyond that.
In C++ with 1 s, roughly:
The classic signals, for C++ at about one second. In Python, expect each bound to drop by roughly a factor of 10 or more for the polynomial rows.
| constraint | aim for | what that usually means |
|---|---|---|
| n ≤ 10 | O(n!) | try every ordering (permutations, backtracking)· Subsets and permutations |
| n ≤ 20 | O(2ⁿ · n) | try every subset, bitmasks· Subsets and permutations |
| n ≤ 400 | O(n³) | three nested loops, DP over ranges |
| n ≤ 5,000 | O(n²) | every pair, DP over pairs of positions |
| n ≤ 10⁶ | O(n log n) | sort first, binary search inside a loop, a heap· Merge sort and inversions, The first-true template |
| n ≤ 10⁷ or so | O(n) | one pass: two pointers, sliding window, hashing, prefix sums· Opposite ends, Sliding window: fixed and variable windows, Seen-set and complement, Prefix sums in 1D and 2D |
| n up to 10⁹ or 10¹⁸ | O(log n), O(√n) or O(1) | binary search on the value, maths; you can't even read n items· Search on the answer |
Your solution is O(n³). n = 10⁹ · C++, 1 s. Will it pass?