Is my solution fast enough? Reading constraints like a pro
Every problem lists constraints, such as 1 ≤ N ≤ 100,000. They are not decoration: they tell you how fast your solution needs to be. Learning to read them saves you from writing a slow solution, submitting it and running out of time.
The basic idea
A computer can do roughly a few hundred million simple operations per second in C++. Python is much slower, often 10 to 100 times. So count how many operations your idea needs for the largest input, and compare.
On RelayTrixCode each test usually has 1 to 2 seconds, depending on how many tests a problem has.
Quick reference
A rough guide for C++, for the largest N in the constraints:
| Largest N | Usually fine | Example idea |
|---|---|---|
| Up to about 10 | O(N!) or O(2^N · N) | Try every order or every subset |
| Up to about 20 | O(2^N) | Try every subset |
| Up to about 500 | O(N^3) | Three nested loops |
| Up to about 5,000 | O(N^2) | Two nested loops |
| Up to about 1,000,000 | O(N log N) | Sorting, binary search, heaps |
| Larger than that | O(N) or O(log N) | One pass, or a formula |
A worked example
Suppose N can be 100,000 and your idea compares every pair of elements. That is about N × N = 10 billion comparisons: far too many. If you sort first and then make one pass, it becomes about N log N, roughly 1.7 million steps, which runs in a few milliseconds.
Do not forget the values
- Value limits matter too. If numbers can reach 1,000,000,000 and you add two of them, the result no longer fits in a 32-bit int. Use a 64-bit type such as long long in C++ or long in Java.
- Watch the total input size. Several test lines of 100,000 numbers each need fast input reading.
- Memory counts as well. An array of 100 million integers needs about 400 MB, more than most judges allow.
Use Run to check, not to guess
Examples are small, so passing them does not prove your solution is fast. Before you submit, estimate the work for the largest input. If you are close to the limit, look for a faster idea first.