Why measure efficiency?#
Two programs can give the same answer but one finishes in a blink and the other takes hours. When IRCTC handles crores of searches or Google ranks billions of pages, the algorithm decides whether the system works at all.
We don't measure in seconds (that depends on the computer). We count how the number of steps grows as the input size n grows. This is asymptotic analysis, written in Big-O notation.
Big-O बताता है कि input बड़ा होने पर program का काम कितनी तेज़ी से बढ़ता है। अगर 10 items के लिए 10 steps और 1000 items के लिए 1000 steps लगें तो वह O(n) है। अगर 1000 items के लिए 10 लाख steps लगें तो O(n²) - जो बड़े data पर बहुत धीमा हो जाता है।
Common complexity classes#
| Big-O | Name | Example | n = 1,000,000 |
|---|---|---|---|
| O(1) | constant | array index a[i], push to a stack |
1 step |
| O(log n) | logarithmic | binary search | ~20 steps |
| O(n) | linear | find max, linear search | 10⁶ |
| O(n log n) | linearithmic | merge sort, std::sort |
~2×10⁷ |
| O(n²) | quadratic | bubble sort, all pairs | 10¹² - too slow |
| O(2ⁿ) | exponential | all subsets, naive Fibonacci | impossible |
A rough rule for competitive programming: a computer does about 10⁸ simple operations per second. If n = 10⁵, an O(n²) solution (10¹⁰) will time out, but O(n log n) (~2×10⁶) is fine.
Rules for simplifying#
- Drop constants - O(2n) → O(n), O(n/2) → O(n).
- Keep the biggest term - O(n² + n + 50) → O(n²).
- Sequential steps add - a loop of n then a loop of m → O(n + m).
- Nested steps multiply - a loop of n inside a loop of m → O(n × m).
Analysing code#
Single loop: 8 Nested loops: 64 All pairs: 28 Halving loop: 3
Notice "all pairs" does n(n-1)/2 steps - half of n², but still O(n²) because we drop the constant ½.
Best, average and worst case#
Linear search for a value in an array of n items:
- Best case - it's the first item: 1 step.
- Worst case - it's the last item or missing: n steps → O(n).
- Average case - about n/2 steps → still O(n).
Big-O usually describes the worst case, because that's the guarantee.
Space complexity#
Space complexity counts the extra memory an algorithm needs.
- Summing an array with one variable → O(1) extra space.
- Making a copy of the array → O(n) space.
- A recursive function that goes n calls deep → O(n) space for the call stack.
Recursion and complexity#
fib(25) = 75025 using 242785 calls fib(25) = 75025 using 25 loop steps
The same answer - 242,785 function calls versus 25 steps. Choosing the right algorithm matters more than a faster computer.
Storing answers you already computed (called memoisation or dynamic programming) turns the naive O(2ⁿ) Fibonacci into O(n).
Summary#
- Big-O describes how work grows with input size n - usually the worst case.
- Order: O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ).
- Drop constants and lower terms; sequential steps add, nested steps multiply.
- Space complexity counts extra memory, including the recursion stack.