Reading complexity from code: loops, recursion and hidden costs

Video lessonComing soon

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, i goes 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:

1021324354657687
i = 8
1021324354657687
i = 4, after 1 turn
1021324354657687
i = 2, after 2 turns
1021324354657687
i = 1, after 3 turns

Two pointers start at both ends and move towards each other, so together they cover the array once:

1031426384115leftright
Each turn moves one pointer one step inwards

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) calls sumTo(3), and so on down to sumTo(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)
    
120314120
The calls made by fib(4): 9 in all

Recursion also uses memory. Every open call waits on the call stack, so sumTo(n) uses O(n) space, even without an array.

5 Hidden costs: one line, many steps

Some lines look like one step but run a loop inside the library. Inside a loop over n, one of them turns O(n) into O(n²).

The lineWhat it doesCost
contains, indexOf, find, x in listChecks the values one by oneO(n)
remove(0), pop(0), erase(begin())Moves every other value leftO(n)
s = s + c on a stringCopies the whole stringO(length of s)
substr, substring, s[a:b], sliceCopies the pieceO(length of piece)
max, min, sum, countReads every valueO(n)
SortingSorts the whole arrayO(n log n)
  • Strings in a loop. s += c adds to the end in about one step. But s = s + c builds a new string each time, so it costs as much as the string is long.
  • Slices in Go and Rust. s[a:b] and &s[a..b] share the same memory, so they cost one step. Elsewhere a slice is a copy.
  • Sorting inside a loop. Sorting once costs O(n log n). Sorting on each of n turns costs O(n² log n).

Reading nums[i], adding to the end of a list, and checking a hash set or map each cost about one step.

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:

xresult beforeValues checkedAdded?
4[]0Yes
2[4]1Yes
4[4, 2]1No
7[4, 2]2Yes
2[4, 2, 7]2No
9[4, 2, 7]3Yes

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 j never 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.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.