Reading complexity from code: loops, recursion and hidden costs
1 Counting the work in code
Before we submit, we want to know if the code is fast enough at the largest input. The last lesson showed what O(n) and O(n²) mean. This lesson reads them off the code.
The method is the same for any code. We find the parts that repeat: loops and function calls. We count how often each one runs for an input of size n, multiply by the work in one run, and keep the biggest term.
A line that runs once, such as sum = 0, costs O(1). Next to a loop it does not matter.
2 Loops one after another, loops inside loops
-
One after another: add. Two loops over n run n + n = 2n steps. We drop the 2, so it is O(n).
for i from 0 to n - 1 sum = sum + nums[i] for i from 0 to n - 1 print nums[i] -
One inside another: multiply. The inner loop runs n times for each of the n outer turns, so it is O(n²).
for i from 0 to n - 1 for j from 0 to n - 1 compare nums[i] and nums[j] -
Inner loop from i + 1: still O(n²). The inner loop gets one turn shorter each time. For n = 8 it runs 7 + 6 + … + 1 = 28 times, about n²/2.
for i from 0 to n - 1 for j from i + 1 to n - 1 compare nums[i] and nums[j] -
Two different inputs: keep both sizes. A loop over a string of length n with a loop over a string of length m inside is O(n × m), not O(n²). One of the strings might be tiny.
At n = 10⁵, O(n²) is around 10¹⁰ steps. At about 10⁸ steps a second, that gets TLE.
3 Loops that halve, double or meet
Not every loop runs n times. The count comes from how the loop variable changes.
-
Halve: O(log n). For n = 8,
igoes 8, 4, 2, 1, so the loop stops after 3 turns. In general it runs about log₂ n times, only about 20 for n = 10⁶.i = n while i > 1 i = i / 2 -
Double: O(log n). A loop that goes 1, 2, 4, 8, … and stops at n is the same count from the other side.
-
Halve inside a loop over n: O(n log n). Each of the n outer turns does about log n work.
for i from 0 to n - 1 j = n while j > 1 j = j / 2 -
Two pointers that meet: O(n). Each turn moves one pointer one step closer to the other. The gap starts at n − 1, so the loop runs at most n − 1 times.
left = 0 right = n - 1 while left < right if nums[left] + nums[right] == target return true else if nums[left] + nums[right] < target left = left + 1 else right = right - 1 return false
Halving keeps only half of what is left each turn, so 8 values are down to 1 after 3 turns:
Two pointers start at both ends and move towards each other, so together they cover the array once:
4 Recursion: count the calls
For recursion, we count the calls in total, then multiply by the work one call does on its own.
-
One call on n − 1: O(n).
sumTo(4)callssumTo(3), and so on down tosumTo(0). That is n + 1 calls, each doing one step.function sumTo(n) if n == 0 return 0 return n + sumTo(n - 1) -
One call on n / 2: O(log n). The input halves on every call, as in binary search.
-
Two calls each: O(2ⁿ). Each level can hold twice as many calls as the one above. With about n levels, that is up to about 2ⁿ calls.
function fib(n) if n <= 1 return n return fib(n - 1) + fib(n - 2)
Recursion also uses memory. Every open call waits on the call stack, so sumTo(n) uses O(n) space, even without an array.
6 A real function with a hidden cost
We want to remove the repeats from nums, keeping each value where it first appears. For [4, 2, 4, 7, 2, 9], the answer is [4, 2, 7, 9]. A first try adds each value to the result unless the result already has it.
There is one loop, so it looks like O(n). But the check reads the result one value at a time:
x | result before | Values checked | Added? |
|---|---|---|---|
| 4 | [] | 0 | Yes |
| 2 | [4] | 1 | Yes |
| 4 | [4, 2] | 1 | No |
| 7 | [4, 2] | 2 | Yes |
| 2 | [4, 2, 7] | 2 | No |
| 9 | [4, 2, 7] | 3 | Yes |
When every value is different, every check reads the whole result. The checks add up to 0 + 1 + … + (n − 1), the triangle from section 2, so the function is O(n²) and gets TLE.
The result stays a list, because the order matters, but the check does not need one. We keep a hash set of the values seen so far beside it. It answers "is x in here?" in about one step on average.
Now the time is O(n), and the set adds O(n) space. Go has no set type, so a map to true does the job.
7 Mistakes when reading complexity
-
Calling every nested loop O(n²). Here
jnever goes back to 0. It moves from 0 to n once in the whole run, so the code is O(n). Sliding window methods depend on this.j = 0 for i from 0 to n - 1 while j < n and nums[j] <= nums[i] + 10 j = j + 1 -
Treating a string as one step. Comparing two strings or hashing one reads every character. Checking n words of length up to m against a set is O(n × m), not O(n).
-
Slicing inside recursion. Each of the n calls copies the rest of the array, so this is O(n²). Passing an index instead brings it back to O(n).
function sumList(nums) if nums is empty return 0 return nums[0] + sumList(nums[1 to end])
The habit to keep: before submitting, point at every loop, recursive call and library call inside a loop, and say how often each runs at the largest n. The next lesson starts from the constraints instead.
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.