ANCO

Big O Notation

ANCO, as with USACO and all other competitive programming contests, have something known as a “time limit” for every question.

Basically, if your code doesn't finish running in 2 seconds or less, your code will be marked as wrong due to a Time Limit Error (TLE), even if it produces the correct answer! This is because a computer can only do 10^8 operations per second, and thus some correct but extremely slow solutions would time out.

As a result, Big O notation is very important to know for this contest, as it allows you to decipher what type of solution to write for a certain problem.

Every problem will have a different input size denoted as N, and you will see things like N≤ 105, N ≤ 103, or N≤ 100. That maximum bound of N (e.g. 105, 103, 100) is actually VERY important; it allows you to know what kind of solution you must write.

ConstraintComplexityNotes
N > 105O(1)Your solution must have exactly one operation to it.
N ≤ 105O(N)The solution must be determined after one (or multiple, if not nested) runthroughs of the input data. ABSOLUTELY NO NESTED LOOPS, unless the nested loop is an “if” condition that runs in constant time.
N ≤ 103O(N2)One for-loop nested inside a certain for-loop is allowed.
N ≤ 100O(N3)Two for-loops nested inside a certain for-loop is allowed.

Note that a factor of (log N) can be added at the end of any kind of solution for virtually no change in runtime. (So when N ≤ 105, an O(N log N) solution is also feasible, likewise for N≤ 103, an O(N2 log N) solution is feasible, etc.)

If there are two or more input variables for a certain problem (e.g. some problems may have a certain amount of test cases inside each test case denoted as T), a rule of thumb is that when variable values are multiplied together, the result should be less than 108 if you want the code to be fast enough.

For example, if T = 103 and N = 103, an O(TN) solution is fast enough (T×N = 106 < 108), but it is not fast enough if T = 105 (T×N = 108 ≥ 108). Similarly, if we were to introduce a third variable K where K = 5, then an O(TNK) solution would be fast enough (T×N×K= 5×106 < 108), but if K = 103, then it would not be fast enough (T×N×K = 109≥ 108).

Want to see how nesting loops affects complexity in real time?

Open the Big O Visualizer →