Kodewick
Start learning →
Big O: O(1), O(n), O(n²)2 / 50

Big O: O(1), O(n), O(n²)

Lesson 2 of 50 · Part 1 · Getting started: how fast · about 15 minutes

Big O says how fast the number of steps grows with n: drop the constants and keep only the fastest-growing term, so 3n + 2 is O(n), a fixed number of steps is O(1) and two nested loops are O(n²).

The last lesson counted steps: finding the largest is about n steps, two nested loops about n². Big O is the short way to say that: O(n), O(n²). It doesn't care whether it's 3n + 2 or 5n, only about how it grows.

Common kinds of growth: O(1) stays flat, O(log n) grows very slowly, O(n) is a straight line, O(n log n) a little faster, O(n²) shoots up

What Big O says

Writing Big O takes two moves:

  1. Drop the constant factor: 3n and n are both O(n). A constant changes the size a few times, not the growth.
  2. Keep only the largest term: n² + 100n + 7 is O(n²). Once n is large, the rest hardly counts.

So 3n + 2 is O(n), n²/2 + n/2 is O(n²), and 20 is O(1).

Choose one

What is 3n² + 5n + 100 in Big O?

Choose allPick all that apply

Which of these are O(n)? You can pick more than one.

O(1): nothing to do with n

Getting one element of an array by its index takes one step to work out the address and one to fetch it, however long the array is.

main.c
1#include <stdio.h>2 3int main(void) {4    int a[100000];5    a[99999] = 42;6    // however long the array, a[i] is this one step7    printf("%d\n", a[99999]);8    return 0;9}
Output
42

Swapping two variables, working out one expression, a return: all O(1), a fixed number of steps.

a4927501234↑i

Reading a[3]: the start address plus the size of 3 elements gives its place at once, no counting from the front
Choose one

n is the length of the array. Which piece of code is O(1)?

O(n): one pass

Looking for a number in an array may mean looking at every element, in the worst case.

a (looking for x = 7)4925701234↑i
1for (int i = 0; i < n; i++)2    if (a[i] == x)3        return i;4return -1;

Looking for 7 one by one: at worst n looks, O(n)

One loop doing O(1) work each time is O(n) altogether.

Choose one

An O(n) program takes 1 millisecond for n = 1000. About how long does it take for n = 4000?

O(n²): two nested loops

To ask "is any number in the array there twice", the plainest way compares every pair:

main.c
1#include <stdio.h>2 3int has_dup(int a[], int n) {4    for (int i = 0; i < n; i++)5        for (int j = i + 1; j < n; j++)6            if (a[i] == a[j])7                return 1;8    return 0;9}10 11int main(void) {12    int a[] = {3, 8, 1, 9, 8};13    printf("%d\n", has_dup(a, 5));14    return 0;15}
Output
1
Choose oneA wrong guess is fine

The inner loop only goes up to i. With n = 6, what does it print, and what is its Big O?

1#include <stdio.h>2 3int main(void) {4    int n = 6, steps = 0;5    for (int i = 0; i < n; i++)6        for (int j = 0; j < i; j++)7            steps++;8    printf("%d\n", steps);9    return 0;10}
Choose one

An O(n²) program takes 1 second for n = 1000. About how long does it take when n becomes 2000?

Exercise 1

Is anything there twice

Finish has_dup: compare every pair with two loops and return 1 if a number appears twice, 0 if not. Make the program print the two lines below.

It should print
1
0
exercise1.c
1#include <stdio.h>2 3int has_dup(int a[], int n) {4    // compare every pair5    return 0;6}7 8int main(void) {9    int a[] = {3, 8, 1, 9, 8};10    int b[] = {3, 8, 1, 9, 7};11    printf("%d\n%d\n", has_dup(a, 5), has_dup(b, 5));12    return 0;13}
Output
Press Run or Ctrl+Enter

Reading Big O off the code

No need to count every time. Three rules:

The code looks likeBig OWhy
One part after another (a loop, then another loop)the largest partO(n) + O(n) is O(n); O(n) + O(n²) is O(n²)
A loop inside a loopmultiplyn outer × n inner = O(n²)
The size halves every timeO(log n)the next lesson

In an exam or an interview: to find the time complexity, find the innermost statement, write how many times it runs as a formula in n, then drop the constants and the small terms.

int cnt = 0;①for (int i = 0; i < n; i++)②    for (int j = 0; j < n; j++)③        if (a[i] == a[j]) cnt++;④for (int k = 0; k < n; k++)⑤    sum += a[k];
  1. ①outside the loops, once: O(1), ignore it
  2. ②outer loop: i from 0 to n − 1, n times
  3. ③for each outer round, the inner loop runs n times
  4. ④the innermost statement: n × n = n² times
  5. ⑤the part after it: n times, added to the two loops
Reading code this way: two nested loops, n × n, then one more loop, n: n² + n in all, keep the largest term: O(n²)
Choose one

What's the Big O of this code?

1for (int i = 0; i < n; i++)2    for (int j = 0; j < n; j++)3        for (int k = 0; k < n; k++)4            cnt++;
Choose one

There is only one loop. What is its Big O?

1for (int i = 0; i < n * n; i++)2    cnt++;
Exercise 2

One part after another

First one loop of n rounds, then two nested loops of n × n. Finish the counting and print the total for n = 10.

It should print
110
exercise2.c
1#include <stdio.h>2 3int main(void) {4    int n = 10, steps = 0;5    for (int i = 0; i < n; i++)6        steps++;7    // now two nested loops, n rounds each, adding 1 to steps every time8    printf("%d\n", steps);9    return 0;10}
Output
Press Run or Ctrl+Enter

Best, worst and average

The same code can take a different number of steps on different data. Take linear search: if the number you want is the first one, one look and you are done; if it is the last one, or not there at all, you have to look at all n.

best: find 4search(a, 5, 4)1 lookit's the first one
worst: find 6search(a, 5, 6)5 looksonly after looking at all of them do you know it's not there
The same linear search, looking for different numbers in the 5 numbers 4 9 2 5 7
main.c
1#include <stdio.h>2 3int looks = 0;4 5int search(int a[], int n, int x) {6    for (int i = 0; i < n; i++) {7        looks++;8        if (a[i] == x) return i;9    }10    return -1;11}12 13int main(void) {14    int a[] = {4, 9, 2, 5, 7};15    int xs[] = {4, 2, 6};16    for (int k = 0; k < 3; k++) {17        looks = 0;18        int at = search(a, 5, xs[k]);19        printf("find %d: index %d, %d looks\n", xs[k], at, looks);20    }21    return 0;22}
Output
find 4: index 0, 1 looks
find 2: index 2, 3 looks
find 6: index -1, 5 looks
  • Best case: the data that takes the fewest steps. For linear search that is 1 look, O(1).
  • Worst case: the data that takes the most steps. For linear search that is n looks, O(n).
  • Average case: if the number is equally likely to be at any position, it takes (1 + 2 + … + n) / n = (n + 1) / 2 looks on average: still O(n).

When people say "linear search is O(n)", they mean the worst case: however unlucky you are, it is never slower than that. If a question doesn't say which case, answer for the worst one.

Guess the outputA wrong guess is fine

Checking for repeats by comparing every pair once, stopping as soon as one is found. How many comparisons for these numbers?

1#include <stdio.h>2 3int main(void) {4    int a[] = {5, 5, 1, 9, 3};5    int n = 5, cmp = 0, found = 0;6    for (int i = 0; i < n && !found; i++)7        for (int j = i + 1; j < n && !found; j++) {8            cmp++;9            if (a[i] == a[j]) found = 1;10        }11    printf("%d\n", cmp);12    return 0;13}
Choose one

Linear search over n numbers; the number you want is definitely in the array and equally likely to be at any position. How many comparisons does it take on average?

Summary

Take-away

Big O: drop the constants, keep the fastest-growing term

  • O(1): a fixed number of steps; O(n): one pass; O(n²): two nested loops
  • One part after another: the largest; a loop inside a loop: multiply
  • Count how often the innermost statement runs
  • Best, worst and average can differ; if nobody says which, it's the worst case
1a[i];                          // O(1)2for (i = 0; i < n; i++) ...    // O(n)3for (i...) for (j...) ...      // O(n²)