Skip to the content

Lesson 115 of 296

Big-O: time complexity

What you will learn

  • Why we measure algorithms by how they grow
  • What Big-O notation means
  • The common complexities, from fastest to slowest
  • How to work out the Big-O of your own code
  • The rules for simplifying Big-O
On this page

Why measure growth?

Two solutions can both give the right answer. One finishes in a millisecond for a million items; the other takes hours. Timing code on your laptop is not reliable (computers differ, inputs differ). Instead we ask:

"As the input gets bigger, how does the number of steps grow?"

The size of the input is called n: the number of items in an array, characters in a string, nodes in a tree.

Big-O notation

Big-O describes how the running time grows as n grows, usually in the worst case. It ignores small details and focuses on the shape of the growth.

Big-ONameExampleSteps when n = 1,000
O(1)ConstantRead arr[5], map.get(key)1
O(log n)LogarithmicBinary searchabout 10
O(n)LinearOne loop over the array1,000
O(n log n)LinearithmicGood sorting algorithmsabout 10,000
O(n²)QuadraticA loop inside a loop over the same array1,000,000
O(2ⁿ)ExponentialTrying every subsetmore than the atoms in the universe
O(n!)FactorialTrying every orderingeven more

(O(n²) is said "O of n squared". O(2ⁿ) is "O of 2 to the n".)

What each one means in plain words

  • O(1): the same time however big the input. Looking up by index or by key.
  • O(log n): each step halves the problem. Doubling the input adds only one step. log₂ of 1,000,000 is about 20.
  • O(n): look at each item once.
  • O(n log n): sorting. Slightly more than linear.
  • O(n²): compare every item with every other item.
  • O(2ⁿ): every item is either in or out, and you try all combinations.

Working out the Big-O of code

One loop: O(n)

TypeScript
function sumAll(nums: number[]): number {
  let total = 0;
  for (const n of nums) total += n;
  return total;
}

A loop inside a loop: O(n²)

TypeScript
function hasDuplicateSlow(nums: number[]): boolean {
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] === nums[j]) return true;
    }
  }
  return false;
}

The inner loop runs about n times for each of the n outer turns: about n × n / 2 steps, which is O(n²).

Two loops one after another: O(n + n) = O(n)

TypeScript
function minAndMax(nums: number[]): [number, number] {
  let min = Infinity;
  let max = -Infinity;
  for (const n of nums) min = Math.min(min, n);
  for (const n of nums) max = Math.max(max, n);
  return [min, max];
}

Halving each time: O(log n)

TypeScript
function countHalvings(n: number): number {
  let steps = 0;
  while (n > 1) {
    n = Math.floor(n / 2);
    steps++;
  }
  return steps;
}

The simplification rules

  1. Drop constants. O(2n) is O(n). O(500) is O(1). We care about the shape, not the exact count.
  2. Keep only the biggest term. O(n² + n) is O(n²), because n² dominates as n grows.
  3. Different inputs get different letters. Looping over array a then array b is O(a + b), not O(n). A loop over a inside a loop over b is O(a × b).

Hidden costs in JavaScript

Some built-in methods are loops themselves:

OperationCost
arr[i], arr.push, arr.popO(1)
arr.shift, arr.unshiftO(n): every item moves
arr.includes, indexOf, findO(n)
arr.slice, [...arr], concatO(n): copies
arr.sortO(n log n)
map.get, map.set, set.hasO(1) on average
str + str in a loopCan be O(n) per join; prefer an array and join (Lesson 120)
Object.keys(obj)O(number of keys)

So this looks like one loop but is O(n²):

TypeScript
function uniqueSlow(nums: number[]): number[] {
  const result: number[] = [];
  for (const n of nums) {
    if (!result.includes(n)) result.push(n);
  }
  return result;
}

includes loops over result every time. Replacing the array with a Set makes it O(n) (Lesson 122).

What is fast enough?

A rough guide for coding tests, where about 10 to 100 million simple steps take around a second:

Input size nUsually acceptable
up to about 10 to 20O(2ⁿ), O(n!)
up to about 500O(n³)
up to about 5,000 to 10,000O(n²)
up to about 1,000,000O(n log n) or O(n)
largerO(log n) or O(1)

The constraints in a problem ("1 ≤ n ≤ 100,000") are a hint about the expected complexity.

How to say it in an interview

"Big-O describes how running time grows with input size in the worst case, ignoring constants and lower-order terms. A single loop is O(n), nested loops over the same input are O(n squared), halving the problem each step is O(log n), and good sorts are O(n log n). I watch for hidden loops like includes, shift or slice inside a loop, and I use the input constraints to judge what complexity is needed."

Key words

WordMeaning
AlgorithmA step-by-step method to solve a problem
Time complexityHow the number of steps grows with input size
Big-ONotation for the upper bound of that growth
nThe size of the input
Constant / linear / quadraticO(1) / O(n) / O(n²)
LogarithmicO(log n): halving the problem each step

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.