Lesson 1.2 · Big-O and Complexity
Growth Rates and Reading Constraints
The common complexity classes from fastest to slowest, and how the input limits in a problem tell you which ones will pass.
15 min
Think of it like this
Constraints are like a speed limit sign. If the sign says n can be 100,000, a solution that does n² = 10 billion steps is a car that won't arrive before the deadline, however good the driver is.
1.The ladder of growth rates
From fastest to slowest: O(1) constant, O(log n) logarithmic, O(n) linear, O(n log n) (good sorting), O(n²) quadratic (all pairs), O(n³) cubic (all triples), O(2ⁿ) exponential (all subsets), O(n!) factorial (all orderings).
The gaps are enormous. For n = 100,000: log n ≈ 17, n log n ≈ 1.7 million, n² = 10 billion.
public class Main {
public static void main(String[] args) {
long[] sizes = {10, 1_000, 100_000};
for (long n : sizes) {
double log = Math.log(n) / Math.log(2);
System.out.printf("n=%-7d log=%-5.0f nlogn=%-10.0f n2=%d%n", n, log, n * log, n * n);
}
}
}Output
n=10 log=3 nlogn=33 n2=100
n=1000 log=10 nlogn=9966 n2=1000000
n=100000 log=17 nlogn=1660964 n2=100000000002.Turning constraints into a target
A typical judge allows about 1 second, and Java does roughly 10⁸ simple steps per second. Divide, and the constraint tells you the slowest complexity that still passes:
n ≤ 10 → O(n!) is fine (try every order). n ≤ 20 → O(2ⁿ) (try every subset). n ≤ 500 → O(n³). n ≤ 5,000 → O(n²). n ≤ 10⁵ to 10⁶ → O(n log n) or O(n). n ≤ 10⁹ or more → O(log n) or O(1), usually maths or binary search on the answer.
So before designing anything, read the constraints and write down your target. It rules out whole families of ideas immediately.
Quick check
A problem says 1 ≤ nums.length ≤ 10⁵. You have an O(n²) idea. Will it pass?
Remember
- O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ) < O(n!).
- Budget about 10⁸ simple steps per second.
- Read constraints first and set a target complexity before choosing an approach.
Common mistakes
- Designing a solution before reading the constraints.
- Assuming small test examples mean small real inputs.
- Forgetting that a hidden constant (like 26 letters or a log factor) still counts when n is huge.