Algorithms

Big O notation: what happens when the input doubles

Cover of the article Big O notation: what happens when the input doubles
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. What is Big O notation?
  2. Why count steps and not seconds?
  3. What are the most common complexity classes?
  4. How do you count the steps in Python, PHP and C?
  5. What happens when the input doubles?
  6. How do you get to Big O from the count?
  7. Now you ask: is an O(n) algorithm always faster than an O(n²) one?
  8. What are the most common mistakes with Big O notation?
  9. Now it’s your turn!

Big O notation is a way of saying how much the number of steps of an algorithm can grow, at most, when the size of the input grows. It’s also called Big-Oh notation. You read O(n) as “O of n”, O(n²) as “O of n squared”, and so on.

You already have everything you need to understand it. A step is one pass of a loop. The two main examples are linear search and binary search. And the difference between them has to do with the logarithm. After this article, sentences like “this algorithm is O(n²)” will stop being alphabet soup.

Imagine you’re looking for a name on an attendance list with no order at all. The only way is to read the names one by one. If the list doubles in size, the work doubles. Now look up a word in a paper dictionary. You open it in the middle, see whether the word comes before or after that page, and discard half of the book. If the dictionary doubles in size, you make just one more opening. Both tasks are “searching”, but they grow in very different ways. Big O notation gives a name to that difference.

What is Big O notation?

It’s a classification by growth rate. We call n the size of the input, for example the number of elements in an array, and T(n) the number of steps the algorithm takes. Saying that T(n) is O(n) means that the steps grow, at most, in the same proportion as n.

The formal definition is this:

T(n) is O(f(n)) if there are positive constants c and n0 such that

    T(n) ≤ c × f(n)    for all n ≥ n0

In plain English: from a certain input size on, the steps of the algorithm never go beyond a multiple of f(n). Big O is therefore an upper bound. It’s usually used to describe the worst case, which is the input that takes the most work.

Why count steps and not seconds?

Because the time in seconds depends on the computer. The same algorithm takes different times on different machines, and the difference between them is a constant factor. What doesn’t change from one machine to another is the way the work grows. The question stops being “how long does it take?” and becomes “what happens if the input doubles?”.

What are the most common complexity classes?

  • O(1), constant: the number of steps doesn’t depend on the size of the input.
  • O(log n), logarithmic: at each step, the problem is cut in half.
  • O(n), linear: one step for each element.
  • O(n log n): for each element, a logarithmic amount of work.
  • O(n²), quadratic: for each element, one step for each of the others. That’s what happens in the quadratic function of the program below, with one loop inside another.
  • O(2ⁿ), exponential: each extra element doubles the work.
Chart of the number of steps as the input size grows for the classes O(1), O(log n), O(n), O(n log n) and O(n²), with the quadratic curve climbing much faster
With few elements, the curves stay close together. As n grows, the quadratic one pulls away from all the others.

How do you count the steps in Python, PHP and C?

Each function below represents a class. Instead of measuring time, they count how many times the innermost part runs. In both searches, the value we’re looking for isn’t in the array, which is the worst case.

Python:

# Big O notation: counting the steps of five algorithm patterns

def constant_time(n):
    # looking at the first element: 1 step, no matter the size
    return 1

def logarithmic(n):
    # binary search for a value that isn't in the array: cuts it in half at each step
    steps = 0
    start, end = 0, n - 1
    while start <= end:
        steps += 1
        middle = (start + end) // 2
        start = middle + 1              # the value we want is larger than all of them
    return steps

def linear(n):
    # linear search for a value that isn't in the array: looks at all of them
    steps = 0
    for i in range(n):
        steps += 1
    return steps

def n_log_n(n):
    # for each element, a loop that doubles until it reaches n
    steps = 0
    for i in range(n):
        j = 1
        while j < n:
            steps += 1
            j = j * 2
    return steps

def quadratic(n):
    # compare each element with all the ones that come after it
    steps = 0
    for i in range(n):
        for j in range(i + 1, n):
            steps += 1
    return steps

print("      n   constant  logarithmic   linear   n log n   quadratic")
for n in [500, 1000, 2000, 4000]:
    print("%7d  %9d  %11d  %7d  %8d  %10d" % (n, constant_time(n), logarithmic(n), linear(n), n_log_n(n), quadratic(n)))

print()
print("When n doubles from 2000 to 4000, the steps are multiplied by:")
print("  linear:     %.2f" % (linear(4000) / linear(2000)))
print("  n log n:    %.2f" % (n_log_n(4000) / n_log_n(2000)))
print("  quadratic:  %.2f" % (quadratic(4000) / quadratic(2000)))

print()
print("With 1000000 elements: linear search %d steps, binary search %d steps" % (linear(1000000), logarithmic(1000000)))

print()
print("The smaller terms fade away: (2n² + 2n + 2) divided by n²")
for n in [10, 100, 1000, 10000]:
    print("  n = %5d  ->  %.4f" % (n, (2 * n * n + 2 * n + 2) / (n * n)))

print()
print("Exponential: 2 to the power of n")
for n in [10, 20, 30]:
    print("  n = %d  ->  %d" % (n, 2 ** n))

PHP:

<?php
// Big O notation: counting the steps of five algorithm patterns

function constant_time(int $n): int {
    // looking at the first element: 1 step, no matter the size
    return 1;
}

function logarithmic(int $n): int {
    // binary search for a value that isn't in the array: cuts it in half at each step
    $steps = 0;
    $start = 0;
    $end = $n - 1;
    while ($start <= $end) {
        $steps++;
        $middle = intdiv($start + $end, 2);
        $start = $middle + 1;           // the value we want is larger than all of them
    }
    return $steps;
}

function linear(int $n): int {
    // linear search for a value that isn't in the array: looks at all of them
    $steps = 0;
    for ($i = 0; $i < $n; $i++) {
        $steps++;
    }
    return $steps;
}

function n_log_n(int $n): int {
    // for each element, a loop that doubles until it reaches n
    $steps = 0;
    for ($i = 0; $i < $n; $i++) {
        $j = 1;
        while ($j < $n) {
            $steps++;
            $j = $j * 2;
        }
    }
    return $steps;
}

function quadratic(int $n): int {
    // compare each element with all the ones that come after it
    $steps = 0;
    for ($i = 0; $i < $n; $i++) {
        for ($j = $i + 1; $j < $n; $j++) {
            $steps++;
        }
    }
    return $steps;
}

echo "      n   constant  logarithmic   linear   n log n   quadratic\n";
foreach ([500, 1000, 2000, 4000] as $n) {
    printf("%7d  %9d  %11d  %7d  %8d  %10d\n", $n, constant_time($n), logarithmic($n), linear($n), n_log_n($n), quadratic($n));
}

echo "\nWhen n doubles from 2000 to 4000, the steps are multiplied by:\n";
printf("  linear:     %.2f\n", linear(4000) / linear(2000));
printf("  n log n:    %.2f\n", n_log_n(4000) / n_log_n(2000));
printf("  quadratic:  %.2f\n", quadratic(4000) / quadratic(2000));

printf("\nWith 1000000 elements: linear search %d steps, binary search %d steps\n", linear(1000000), logarithmic(1000000));

echo "\nThe smaller terms fade away: (2n² + 2n + 2) divided by n²\n";
foreach ([10, 100, 1000, 10000] as $n) {
    printf("  n = %5d  ->  %.4f\n", $n, (2 * $n * $n + 2 * $n + 2) / ($n * $n));
}

echo "\nExponential: 2 to the power of n\n";
foreach ([10, 20, 30] as $n) {
    printf("  n = %d  ->  %d\n", $n, 2 ** $n);
}

C:

/* Big O notation: counting the steps of five algorithm patterns */
#include <stdio.h>

/* looking at the first element: 1 step, no matter the size */
int constant_time(int n) {
    (void) n;
    return 1;
}

/* binary search for a value that isn't in the array: cuts it in half at each step */
int logarithmic(int n) {
    int steps = 0, start = 0, end = n - 1;
    while (start <= end) {
        steps++;
        int middle = (start + end) / 2;
        start = middle + 1;             /* the value we want is larger than all of them */
    }
    return steps;
}

/* linear search for a value that isn't in the array: looks at all of them */
int linear(int n) {
    int steps = 0;
    for (int i = 0; i < n; i++) {
        steps++;
    }
    return steps;
}

/* for each element, a loop that doubles until it reaches n */
int n_log_n(int n) {
    int steps = 0;
    for (int i = 0; i < n; i++) {
        int j = 1;
        while (j < n) {
            steps++;
            j = j * 2;
        }
    }
    return steps;
}

/* compare each element with all the ones that come after it */
int quadratic(int n) {
    int steps = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            steps++;
        }
    }
    return steps;
}

int main(void) {
    int sizes[] = {500, 1000, 2000, 4000};
    printf("      n   constant  logarithmic   linear   n log n   quadratic\n");
    for (int t = 0; t < 4; t++) {
        int n = sizes[t];
        printf("%7d  %9d  %11d  %7d  %8d  %10d\n", n, constant_time(n), logarithmic(n), linear(n), n_log_n(n), quadratic(n));
    }

    printf("\nWhen n doubles from 2000 to 4000, the steps are multiplied by:\n");
    printf("  linear:     %.2f\n", (double) linear(4000) / linear(2000));
    printf("  n log n:    %.2f\n", (double) n_log_n(4000) / n_log_n(2000));
    printf("  quadratic:  %.2f\n", (double) quadratic(4000) / quadratic(2000));

    printf("\nWith 1000000 elements: linear search %d steps, binary search %d steps\n", linear(1000000), logarithmic(1000000));

    int values[] = {10, 100, 1000, 10000};
    printf("\nThe smaller terms fade away: (2n² + 2n + 2) divided by n²\n");
    for (int t = 0; t < 4; t++) {
        double n = values[t];
        printf("  n = %5d  ->  %.4f\n", values[t], (2 * n * n + 2 * n + 2) / (n * n));
    }

    printf("\nExponential: 2 to the power of n\n");
    for (int n = 10; n <= 30; n += 10) {
        int power = 1;
        for (int i = 0; i < n; i++) {
            power = power * 2;
        }
        printf("  n = %d  ->  %d\n", n, power);
    }
    return 0;
}

Output:

      n   constant  logarithmic   linear   n log n   quadratic
    500          1            9      500      4500      124750
   1000          1           10     1000     10000      499500
   2000          1           11     2000     22000     1999000
   4000          1           12     4000     48000     7998000

When n doubles from 2000 to 4000, the steps are multiplied by:
  linear:     2.00
  n log n:    2.18
  quadratic:  4.00

With 1000000 elements: linear search 1000000 steps, binary search 20 steps

The smaller terms fade away: (2n² + 2n + 2) divided by n²
  n =    10  ->  2.2200
  n =   100  ->  2.0202
  n =  1000  ->  2.0020
  n = 10000  ->  2.0002

Exponential: 2 to the power of n
  n = 10  ->  1024
  n = 20  ->  1048576
  n = 30  ->  1073741824

The three languages count exactly the same steps. Focus on the concept, not the language! The count is a property of the algorithm, not of whoever runs it.

What happens when the input doubles?

Read the output table from top to bottom, column by column. In each row, n doubles.

  • Constant: always 1.
  • Logarithmic: 9, 10, 11, 12. Doubling the input cost one extra step.
  • Linear: the steps double along with n.
  • n log n: a little more than double. From 2000 to 4000, the factor was 2.18.
  • Quadratic: they quadruple. From 2000 to 4000, the factor was 4.00.
Table of the complexity classes: when the input doubles, the steps don’t change in O(1), increase by 1 in O(log n), double in O(n), a little more than double in O(n log n) and quadruple in O(n²)
Doubling the input and watching the steps is a quick way to recognize the class of an algorithm.

Got it? This is a test you can do with any program of yours: run it with n, run it with 2n and compare.

The million line shows how big the difference is. In a sorted array with 1,000,000 elements, linear search takes 1,000,000 steps in the worst case. Binary search takes 20.

See the animation of both searches in an array of 16 positions
Animation comparing linear search, which looks at all 16 positions, with binary search, which discards half at each step and finishes in 5 steps
Linear search looks at all 16 positions. Binary search discards half at each step and finishes in 5.

How do you get to Big O from the count?

With two rules: keep only the term that grows the most, and throw away the constants.

The quadratic function of the program takes exactly n × (n − 1) ÷ 2 steps, that is, n²/2 − n/2. The term that grows the most is n². The constant 1/2 goes away. Result: O(n²). In the same way, an algorithm that takes 2n + 120 steps is O(n), and one that takes 2n² + 2n + 2 steps is O(n²).

The fourth part of the output shows why this is fair. Dividing 2n² + 2n + 2 by n², the result goes from 2.22 to 2.0002 as n grows. The terms 2n and 2 lose importance, and what’s left is a constant multiple of n². That’s the c of the formal definition.

Who would have thought... Exponential is in another category. With n = 30, 2ⁿ is already over 1 billion. None of the other columns of the table would come close to that with n = 30.

Now you ask: is an O(n) algorithm always faster than an O(n²) one?

No. The definition says “for all n from n0 on”, that is, for large inputs. Big O ignores the constants, and with small inputs they count.

Do the math with two imaginary algorithms: one takes 100 × n steps and the other takes n² steps. With n = 10, the first takes 1,000 steps and the second takes 100. The quadratic one wins. With n = 100, the two tie at 10,000. With n = 1,000, the linear one takes 100,000 and the quadratic one takes 1,000,000. From then on, the gap only grows.

IMPORTANT: being O(n) doesn’t mean always taking n steps. If the value we’re looking for is in the first position, linear search ends in 1 step. It’s still O(n), because O(n) is an upper bound: no input of size n makes the algorithm go beyond that.

What are the most common mistakes with Big O notation?

  • Thinking Big O measures seconds. It measures growth, not time.
  • Keeping the constants. You don’t write O(2n) or O(n + 120). Both are O(n).
  • Keeping the smaller terms. O(n² + n) is O(n²).
  • Concluding that O(n²) is slow for any input. With few elements, there may be no difference at all.
  • Counting loops without looking at what they do. Two nested loops don’t always give n². In the n_log_n function, the inner loop doubles the counter, and the total is n log n.
  • Mixing up the worst case with the common case. The Big O of linear search describes the search that finds nothing.
  • Forgetting the prerequisite. Binary search is only O(log n) because the array is sorted.

Now it’s your turn!

On paper:

  • Name the class of each count: 3n + 7; n² + 100n; 5; 4n log n + n; 2ⁿ + n².
  • A quadratic algorithm takes 10,000 steps with n = 100. How many will it take with n = 200? And with n = 1,000?
  • How many steps does binary search take, in the worst case, in an array of 64 positions? Use the function from the article as a guide.

On the computer:

  • Run the quadratic function with n = 8000 and confirm the factor compared with n = 4000.
  • Write a function with three nested loops, count the steps for n = 50 and n = 100, and find out by how much they’re multiplied.
  • Change the linear function so it stops when it finds a value that’s in position 10, and compare the steps with the worst case.

Try it on your own, without asking anyone for the ready-made answer, not even AI!

See you in the next article!

Stay confident!!!

Sources:

  • Princeton University, COS 226 (Robert Sedgewick and Kevin Wayne). Analysis of Algorithms, with the doubling hypothesis, the order-of-growth classifications and performance predicted from the size of the input (PDF, lecture slides).
  • MIT, 6.006 Introduction to Algorithms. Recitation 1, with big O notation as a way of describing how the running time grows without worrying about different computers, compilers or implementations (PDF).
  • MIT OpenCourseWare, 6.042J Mathematics for Computer Science. Big O, with big O as an upper bound on the growth of a function and the pitfalls of asymptotic notation (PDF).
  • Carnegie Mellon University, 15-210. Asymptotics, with the definition by constants c and n0, the small inputs the definition ignores, and the constant factors and lower-order terms that only an exact comparison reveals (PDF).
  • University of Massachusetts Amherst, COMPSCI 311 (Dan Sheldon). Asymptotic Notation and Efficiency, with the formal definition: T(n) is O(f(n)) if T(n) ≤ c·f(n) for all n ≥ n0 (PDF).
  • Virginia Tech, OpenDSA. Asymptotic Analysis and Upper Bounds, with the upper bound, the rules that throw away multiplicative constants and the rare cases in which a large constant makes the algorithm with the lower growth rate impractical.
  • Pat Morin, Open Data Structures. 1.3: Mathematical Background, with big-Oh notation as a set of functions and the comparison between growth rates.
  • Brad Miller and David Ranum, Problem Solving with Algorithms and Data Structures using Python. Big-O Notation, with the dominant term of T(n) and the example 5n² + 27n + 1005, which is O(n²).
  • Cornell University, CS 2112. Asymptotic Complexity, with the bound that only has to hold for sufficiently large n, from some n0 on.
  • MIT OpenCourseWare, 6.00SC. Notes on Big-O Notation, with O(n) + O(n), which is simply O(n), and loops that go through the whole input, which are O(n) (PDF).
  • The examples were run on Python 3.13, PHP 8.3 and GCC 13.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).