M03 · Big O

Counting Operations and Growth Rates: O, Θ and Ω

Timing code tells you about one machine on one day. Counting how many basic operations it performs, as a function of the input size, tells you how it will behave on any machine when the input grows. This lesson turns exact counts into growth classes, defines O, Θ and Ω precisely, and links every rule to a worked exercise whose answer was checked by counting.

~35 minBeginnerC# · Python · Java · C++
Curriculum: M03 Big O · 3 of 3 lessons available

You will be able to

  • Choose a basic operation and an input size, and count how often the operation runs.
  • Reduce an exact count to its growth class by dropping constant factors and lower-order terms.
  • State the formal definitions of O, Ω and Θ and prove a simple bound with explicit constants.
  • Apply the rules for sequential, nested, halving and dependent loops.
  • Explain what Big O hides (constants, small n, memory effects) and spot operations whose cost is not O(1) in C#, Python, Java and C++.

Helpful before this lesson

  • M01 Algorithmic Thinking — Turn a vague task into precise inputs, outputs and constraints, then argue that a solution is correct.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Why count instead of time

A stopwatch measures your code, your hardware, your compiler, the data you happened to use and whatever else the machine was doing. Useful, but it does not tell you what happens when the input is a thousand times larger. Counting does.

Pick:

  • a basic operation: something that takes roughly constant time and dominates the work, such as a comparison, an element write, or a loop iteration;
  • an input size n: the length of the array, the number of nodes, the number of bits.

Then express the count as a function of n. The lab above counts comparisons and iterations for binary search; the linear search lab counts comparisons for the left-to-right scan. On the 64 values, worst case preset binary search runs 7 iterations, ⌊log₂ 64⌋ + 1. A linear scan that does not find the target compares all 64. At a million elements those numbers become 20 and 1,000,000. The linear vs binary search comparison puts the two side by side.

From an exact count to a growth class

Exact counts are often easy to get and awkward to compare:

Code shape Exact count Growth class Exercise
one loop over n items n Θ(n) single loop
two loops in sequence 2n Θ(n) sequential loops
loop stepping by 3 ⌈n/3⌉ Θ(n) step three
inner loop runs i times n(n − 1)/2 Θ(n²) triangular loop
halve until 1 ⌊log₂ n⌋ Θ(log n) halving loop
loop while i² ≤ n ⌊√n⌋ Θ(√n) square-root loop
n times a doubling loop n · ⌈log₂ n⌉ Θ(n log n) loop times log
three nested loops n³ Θ(n³) triple nested

Two simplifications produce the right-hand column:

  1. Keep only the fastest-growing term. n(n − 1)/2 = n²/2 − n/2. For n = 1,000 the n²/2 term is 500,000 and the n/2 term is 500; the second barely matters and matters less as n grows.
  2. Drop the constant factor. n²/2 and n² differ by a factor that does not depend on n. Machines, compilers and languages change constant factors; they do not change the shape of the curve.

Every exercise page draws the measured count next to the scaled reference curve, so you can see the ratio settle to a constant.

O, Ω and Θ, precisely

For functions f and g of n (counts are non-negative):

  • f(n) = O(g(n)) if there are constants c > 0 and n₀ such that f(n) ≤ c · g(n) for every n ≥ n₀. An upper bound: f grows no faster than g.
  • f(n) = Ω(g(n)) if there are constants c > 0 and n₀ such that f(n) ≥ c · g(n) for every n ≥ n₀. A lower bound: f grows at least as fast as g.
  • f(n) = Θ(g(n)) if both hold. A tight bound: f grows exactly like g, up to constant factors.

Example. f(n) = 3n² + 5n + 2. For n ≥ 1, 5n ≤ 5n² and 2 ≤ 2n², so f(n) ≤ 10n²: f = O(n²) with c = 10, n₀ = 1. Also f(n) ≥ 3n² for every n ≥ 0: f = Ω(n²) with c = 3. Therefore f = Θ(n²).

Three consequences people often get wrong:

  • O is only an upper bound. Linear search is O(n), and it is also O(n²) and O(2ⁿ), which are true and useless. When someone writes "binary search is O(log n)" they nearly always mean the tight bound Θ(log n) for the worst case.
  • O, Ω and Θ are not best, worst and average case. Those are different questions. Each case is a function of n, and each of those functions has its own O, Ω and Θ. "The worst case of linear search is Θ(n) and the best case is Θ(1)" is a precise sentence; the next lesson is about the cases.
  • The = is a convention, read as "is in the set". O(n) = n is not a valid statement.

The growth classes

Class Name n = 10 n = 1,000 n = 1,000,000 Typical source
Θ(1) constant 1 1 1 array index, hash lookup (expected)
Θ(log n) logarithmic ≈ 3.3 ≈ 10 ≈ 20 binary search, balanced tree, heap push
Θ(n) linear 10 1,000 10⁶ one pass
Θ(n log n) linearithmic ≈ 33 ≈ 10⁴ ≈ 2 × 10⁷ merge sort, heap sort
Θ(n²) quadratic 100 10⁶ 10¹² all pairs, insertion sort worst case
Θ(n³) cubic 1,000 10⁹ 10¹⁸ naive matrix multiplication
Θ(2ⁿ) exponential 1,024 ≈ 10³⁰¹ — every subset
Θ(n!) factorial 3,628,800 ≈ 4 × 10²⁵⁶⁷ — every ordering

The Big O explorer draws these curves for n up to 64. Turn on the logarithmic y-axis to see them all at once; with a linear axis, 2ⁿ and n! leave the chart almost immediately. The exercises all subsets and all permutations show where the last two rows come from.

The base of a logarithm does not matter inside O: log₂ n = log₁₀ n / log₁₀ 2, a constant factor. That is why we write O(log n) without a base. (A base inside an exponent does matter: 2ⁿ and 3ⁿ are different classes.)

Rules for loops

  • Sequential blocks add. Θ(n) followed by Θ(n²) is Θ(n + n²) = Θ(n²): the larger term wins.
  • Nested loops multiply, when the inner count does not depend on the outer variable. n iterations of a Θ(log n) body cost Θ(n log n).
  • When the inner count depends on the outer variable, sum it. The triangular loop sums to n(n − 1)/2. The shrinking inner loop sums n + n/2 + n/4 + … < 2n, so two nested loops cost only Θ(n). The harmonic loop sums n/i over i and gets Θ(n log n).
  • How fast the loop variable moves decides the count. Adding a constant gives Θ(n) iterations; multiplying or dividing by a constant gives Θ(log n); see doubling a counter.
  • A break helps only if you can bound where it fires. The nested loop with a break is still Θ(n²).
  • Recursion: count calls times work per call, or write a recurrence. The recursive halving and divide and conquer exercises introduce the idea; module M29 covers recurrences in depth.

What Big O hides

  • Constant factors. An algorithm doing 100n operations loses to one doing n² for every n < 100. Several standard-library sorts switch to insertion sort for short ranges for exactly this reason (see elementary sorts).
  • Small inputs. Growth classes describe large n. For n = 20 almost anything is fast.
  • Memory effects. Two Θ(n) traversals can differ by an order of magnitude because one reads contiguous memory and the other chases pointers; the contiguous storage lesson shows why.
  • The cost of a "basic" operation. Comparing two integers is O(1); comparing two strings of length L is O(L). Sorting n strings is O(n log n) comparisons, which is O(L · n log n) character comparisons in the worst case.

Language notes: operations that look O(1) but are not

Language Looks cheap Actual cost
C# items.Count() (LINQ) on an IEnumerable<T> O(1) when the source implements ICollection<T>, otherwise it enumerates everything: O(n)
C# list.Contains(x), list.Insert(0, x) O(n)
Python x in some_list, some_list.index(x) O(n); x in some_set is O(1) on average
Python some_list.pop(0), some_list.insert(0, x) O(n): every element shifts. collections.deque.popleft() is O(1)
Python s = s + "x" in a loop copies the string each time; see string concatenation
Java linkedList.get(i) O(n): it walks from the nearer end
Java arrayList.add(0, x), arrayList.remove(0) O(n)
C++ std::distance(first, last) O(1) for random-access iterators, linear otherwise
C++ v.insert(v.begin(), x) on a std::vector O(n)

Two that are cheaper than people expect: Python's len() is O(1) for built-in containers, and C++ std::list::size() is constant time since C++11.

Common mistakes

  • Multiplying sequential loops (two loops in a row are 2n, not n²) or adding nested ones.
  • Calling a loop logarithmic because it skips elements. Skipping a constant fraction is still linear; only geometric shrinking is logarithmic.
  • Dropping a term that depends on a different input. Θ(n + m) is not Θ(n) unless m ≤ c · n; see the third lesson of this module.
  • Treating O as "exactly". "Quicksort is O(n²)" is true for its worst case and also an upper bound for every case; say Θ when you mean tight.
  • Ignoring hidden costs inside a line of code, such as in, Contains, slicing or string +.

Worked practice

1. Show that 4n + 100 = Θ(n) by giving the constants.

Upper: for n ≥ 100, 100 ≤ n, so 4n + 100 ≤ 5n (c = 5, n₀ = 100). Lower: 4n + 100 ≥ 4n for all n ≥ 0 (c = 4). Both hold, so Θ(n).

2. A loop runs for i in range(n): for j in range(i, n): work(). What is the class?

The inner loop runs n − i times: n + (n − 1) + … + 1 = n(n + 1)/2. Θ(n²). It is the triangular loop mirrored.

3. Is n² = O(n³)? Is n³ = O(n²)?

n² = O(n³) is true (with c = 1, n₀ = 1), though not tight. n³ = O(n²) is false: n³ / n² = n grows without bound, so no constant c works.

4. Binary search on one billion sorted values: at most how many iterations?

⌊log₂ 10⁹⌋ + 1 = 29 + 1 = 30 (2²⁹ ≈ 5.4 × 10⁸ ≤ 10⁹ < 2³⁰ ≈ 1.07 × 10⁹).

Summary

  • Choose a basic operation and an input size; count the operation as a function of n.
  • Keep the leading term and drop its constant: that is the growth class.
  • O is an upper bound, Ω a lower bound, Θ both; none of them means "worst case".
  • Sequential code adds, independent nested loops multiply, dependent loops must be summed, and the speed of the loop variable decides linear versus logarithmic.
  • Big O hides constants, small-n behaviour, memory effects and the cost of operations that look like one step. Check the docs for what each language's operations really cost.

Full implementation

Both searches in four languages, each checked against one shared set of test cases (found, missing, empty, one element, duplicates, extremes) and 2,000 random sorted arrays compared with the language's built-in binary search.

namespace Bekadan.Dsa.Examples.Searching;
 
/// <summary>
/// Binary search over an array sorted in ascending order.
/// Both methods run in O(log n) time and O(1) extra space; neither checks
/// that the input is sorted (that check alone would cost O(n)).
/// </summary>
public static class BinarySearch
{
    /// <summary>
    /// Returns the index of an element equal to <paramref name="target"/>, or -1.
    /// With duplicates, which matching index is returned is unspecified,
    /// the same contract as <see cref="Array.BinarySearch(Array, object)"/>.
    /// </summary>
    public static int IndexOf(ReadOnlySpan<int> values, int target)
    {
        int low = 0, high = values.Length - 1;
        while (low <= high)
        {
            int mid = low + (high - low) / 2; // (low + high) / 2 could overflow int
            if (values[mid] == target)
                return mid;
            if (values[mid] < target)
                low = mid + 1;
            else
                high = mid - 1;
        }
        return -1;
    }
 
    /// <summary>
    /// Returns the index of the first element equal to <paramref name="target"/>, or -1.
    /// Finds the lower bound (the first index whose value is &gt;= target) in a
    /// half-open range [low, high), then checks that one element.
    /// </summary>
    public static int FirstIndexOf(ReadOnlySpan<int> values, int target)
    {
        int low = 0, high = values.Length;
        while (low < high)
        {
            int mid = low + (high - low) / 2;
            if (values[mid] < target)
                low = mid + 1;
            else
                high = mid; // values[mid] may be the first match: keep it
        }
        if (low < values.Length && values[low] == target)
            return low;
        return -1;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Searching/BinarySearch.cs

"""Binary search over a list sorted in ascending order.
 
Both functions run in O(log n) time and O(1) extra space. Neither checks that
the input is sorted: that check alone would cost O(n).
"""
 
from collections.abc import Sequence
 
 
def index_of(values: Sequence[int], target: int) -> int:
    """Return the index of an element equal to target, or -1.
 
    With duplicates, which matching index is returned is unspecified.
    """
    low, high = 0, len(values) - 1
    while low <= high:
        mid = (low + high) // 2  # Python ints never overflow
        if values[mid] == target:
            return mid
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1
 
 
def first_index_of(values: Sequence[int], target: int) -> int:
    """Return the index of the first element equal to target, or -1.
 
    Finds the lower bound (the first index whose value is >= target, which is
    what bisect.bisect_left returns) in a half-open range [low, high), then
    checks that one element.
    """
    low, high = 0, len(values)
    while low < high:
        mid = (low + high) // 2
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid  # values[mid] may be the first match: keep it
    if low < len(values) and values[low] == target:
        return low
    return -1

Tested on CPython 3.14.0 · examples/python/dsa_examples/binary_search.py

package dev.bekadan.dsa.searching;
 
/**
 * Binary search over an array sorted in ascending order. Both methods run in
 * O(log n) time and O(1) extra space; neither checks that the input is sorted
 * (that check alone would cost O(n)).
 */
public final class BinarySearch {
    private BinarySearch() {
    }
 
    /**
     * Returns the index of an element equal to {@code target}, or -1. With
     * duplicates, which matching index is returned is unspecified, the same
     * contract as {@link java.util.Arrays#binarySearch(int[], int)}.
     */
    public static int indexOf(int[] values, int target) {
        int low = 0, high = values.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2; // (low + high) / 2 could overflow int
            if (values[mid] == target) {
                return mid;
            }
            if (values[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }
 
    /**
     * Returns the index of the first element equal to {@code target}, or -1.
     * Finds the lower bound (the first index whose value is &gt;= target) in a
     * half-open range [low, high), then checks that one element.
     */
    public static int firstIndexOf(int[] values, int target) {
        int low = 0, high = values.length;
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (values[mid] < target) {
                low = mid + 1;
            } else {
                high = mid; // values[mid] may be the first match: keep it
            }
        }
        if (low < values.length && values[low] == target) {
            return low;
        }
        return -1;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/searching/BinarySearch.java

#pragma once
 
#include <cstddef>
#include <span>
 
namespace bekadan::dsa {
 
// Binary search over a span sorted in ascending order. Both functions run in
// O(log n) time and O(1) extra space; neither checks that the input is sorted
// (that check alone would cost O(n)).
 
// Returns the index of an element equal to target, or -1. With duplicates,
// which matching index is returned is unspecified.
// Signed indices: with high = size - 1, an empty span must give high = -1.
inline std::ptrdiff_t index_of(std::span<const int> values, int target) {
    std::ptrdiff_t low = 0, high = std::ssize(values) - 1;
    while (low <= high) {
        std::ptrdiff_t mid = low + (high - low) / 2;  // (low + high) / 2 could overflow
        if (values[mid] == target) {
            return mid;
        }
        if (values[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return -1;
}
 
// Returns the index of the first element equal to target, or -1. Finds the
// lower bound (what std::lower_bound returns) in a half-open range
// [low, high), then checks that one element.
inline std::ptrdiff_t first_index_of(std::span<const int> values, int target) {
    std::ptrdiff_t low = 0, high = std::ssize(values);
    while (low < high) {
        std::ptrdiff_t mid = low + (high - low) / 2;
        if (values[mid] < target) {
            low = mid + 1;
        } else {
            high = mid;  // values[mid] may be the first match: keep it
        }
    }
    if (low < std::ssize(values) && values[low] == target) {
        return low;
    }
    return -1;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/binary_search.hpp

References