DEV Community

Devmancer
Devmancer

Posted on

The big-o-notation

When we talk about algorithms, we often describe them using asymptotic notation, and one of the most common types is Big-O notation.

Big-O represents the worst-case time complexity of an algorithm.

But what does that really mean?

Think of it like this:

Big-O asks your code:
“As more customers come in, how crazy does the work become?”

In other words, Big-O measures how your code behaves as the input size gets bigger.

What is “n”?

n represents the size of the input.

For example:

If you have an array with 5 numbers → n = 5

If you have 1000 numbers → n = 1000

Big-O is simply asking:

If n increases, how much do the number of steps increase?

O(1) —> Constant Time
const array = [1, 2, 3, 4];
console.log(array[0]);

This is O(1) —> constant time.

Why?

Because it doesn’t matter if the array has:

4 elements

1,000 elements

1,000,000 elements

Accessing array[0] always takes one step.

The work does not grow as n grows.

O(n) —> Linear Time
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

This is O(n) —> linear time.

Why?

Because the loop runs once for every element.

If there are 5 elements → the loop runs 5 times

If there are 100 elements → the loop runs 100 times

The number of operations grows at the same rate as the input size.

If n doubles, the work doubles.

O(n²) —> Quadratic Time
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
console.log(i, j);
}
}

This is O(n²) —> quadratic time.

Why?

The outer loop runs n times.

For each outer loop, the inner loop also runs n times.

So total operations = n × n = n².

If:

n = 5 → 5 × 5 = 25 operations

n = 100 → 100 × 100 = 10,000 operations

Now the work grows much faster than the input.

If n doubles, the work increases four times.

Important Rule About Big-O

Big-O cares about growth, not exact numbers.

If an algorithm takes:

2n² + 10n + 100

We still write it as:

O(n²)

Why?

Because when n becomes very large, the n² term dominates everything else.

Big-O keeps only the fastest-growing term.

Quick Summary

O(1) → stays the same no matter what

O(n) → grows at the same rate as the input

O(n²) → grows much faster than the input

Big-O measures growth as input increases

We ignore constants and smaller terms

Top comments (0)