Sign in

Understanding time complexity and Big O notation from the ground up

Learn how to quantify the execution efficiency of your code across varying input sizes using Big O notation, asymptotic analysis, and real-world Python examples.

MonksBit Desk

December 4, 2026 · 9 min read · 19 views

Read

Time complexity is a mathematical characterization of how the runtime of an algorithm increases as the size of its input grows. Big O notation expresses this relationship by defining an upper bound on growth, abstracting away hardware differences and low-level constant factors.

You will need. Basic familiarity with Python syntax · Understanding variables, loops, and conditional statements

How well do you know this already?

The full lesson

Level 1 · Beginner: Counting operations and identifying input growth

When evaluating how fast an algorithm runs, measuring wall-clock time in seconds is unreliable. Running the same code on a slow phone produces a different duration than running it on a supercomputer. Background tasks, operating system scheduling, and hardware architectures also distort measurements. Instead of tracking elapsed seconds, computer scientists count the number of fundamental computational steps executed by the code relative to the size of the input.

Consider an input list of size N. If an algorithm performs a single operation regardless of how large N becomes, the number of steps is constant, which we write as O(1). If the algorithm inspects each item in the list once, it performs roughly N steps, which we write as O(N). If the algorithm compares every item in the list to every other item using nested loops, it performs roughly N multiplied by N steps, which we write as O(N^2).

Let us walk through a small example by hand. Suppose we have a list of three elements: [10, 20, 30]. If we check whether the first element equals 10, that takes exactly one comparison. Even if the list had one million elements, checking index 0 still takes one operation. Now suppose we calculate the sum of all elements in [10, 20, 30]. We start at total = 0, add 10, add 20, and add 30. That requires three addition operations for three elements. If the list contained 1,000 items, it would require 1,000 additions. The work scales linearly with input size.

Comparing constant and linear time algorithms on an input list

def get_first_element(numbers):    # Constant time: O(1)    # Always executes exactly one index lookup, regardless of list size.    if not numbers:        return None    return numbers[0]def calculate_sum(numbers):    # Linear time: O(N)    # The loop runs once for every element in the list.    total = 0    for value in numbers:        total += value    return total# Demonstrationsample = [10, 20, 30]print(get_first_element(sample))  # 1 stepprint(calculate_sum(sample))      # 3 steps

Key takeaways

  • Time complexity measures how operation counts scale with input size, not wall-clock seconds.
  • O(1) represents constant time, meaning runtime does not depend on input size.
  • O(N) represents linear time, where running time grows in direct proportion to input size.

Level 2 · Intermediate: Formal Big O rules, loop analysis, and dominant terms

Big O notation formally describes an asymptotic upper bound. When an algorithm performs 3N^2 + 5N + 100 operations, we say its time complexity is O(N^2). We arrive at this simplification by applying two primary rules: drop non-dominant terms and drop multiplicative constants. As N grows to very large numbers such as one billion, the N^2 term vastly outweighs 5N and 100, making lower-order terms negligible.

Similarly, constants are omitted because Big O focuses on growth rate rather than exact counts. An algorithm taking 2N operations and an algorithm taking 100N operations both grow linearly: doubling the input size N doubles their required steps. While constant factors matter in micro-benchmarks, asymptotic notation isolates how the algorithm scales across orders of magnitude.

When reading source code, sequential independent loops have additive complexity, while nested loops have multiplicative complexity. If one loop runs N times and another sequential loop runs M times, the total time is O(N + M). If an outer loop iterates N times and an inner loop executes N times for each outer iteration, the total time is O(N * N) = O(N^2).

We must also distinguish between best-case, average-case, and worst-case scenarios. Consider linear search: if the target item is at index 0, the search stops after one step (best case O(1)). If the target is at the end or absent, it checks all N elements (worst case O(N)). Unless specified otherwise, software engineering discussions assume worst-case complexity to guarantee predictable performance boundaries.

Analyzing additive versus multiplicative complexities and early exits

def find_pairs_and_maximum(numbers):    # Step 1: Find maximum value - O(N)    if not numbers:        return None, []        current_max = numbers[0]    for val in numbers:        if val > current_max:            current_max = val                # Step 2: Generate all pairs - O(N^2)    pairs = []    n = len(numbers)    for i in range(n):        for j in range(n):            pairs.append((numbers[i], numbers[j]))                # Total runtime is O(N) + O(N^2) -> O(N^2) dominant term    return current_max, pairsdef linear_search(numbers, target):    # Best case: O(1) if target is at index 0    # Worst case: O(N) if target is absent or at the last index    for index, val in enumerate(numbers):        if val == target:            return index    return -1

Key takeaways

  • Drop lower-order terms and constant coefficients to determine the asymptotic bound.
  • Sequential independent operations add together: O(A) + O(B) = O(A + B).
  • Nested operations multiply: an inner loop of M steps inside an outer loop of N steps yields O(N * M).
  • Standard Big O claims typically denote worst-case guarantees unless stated otherwise.

Level 3 · Advanced: Logarithmic curves, recursion, and real-world hardware limits

Beyond constant and polynomial complexities exist logarithmic and divide-and-conquer classes: O(log N) and O(N log N). A logarithmic runtime occurs whenever an algorithm halves the remaining problem size in each discrete step. In binary search across a sorted array of size N, the search space reduces from N to N/2, then N/4, until reaching 1. The total number of divisions needed to reach 1 from N is log2(N). When N is one million, log2(N) is approximately 20 operations.

Recursive functions can be evaluated using recurrence relations. A relation defines T(N), the time required to solve a problem of size N, in terms of smaller calls. For instance, merge sort divides an array into two halves of size N/2 and merges them in linear time: T(N) = 2T(N/2) + O(N). Solving this relation using recursion trees or the Master Theorem reveals an overall complexity of O(N log N).

In high-performance software, asymptotic analysis has real-world limits because it ignores hardware cache hierarchies. Modern CPU architectures access data sequentially in L1/L2 caches thousands of times faster than fetching random pointers from main memory (RAM). Consequently, an O(N^2) algorithm with contiguous memory access and tiny constants can sometimes outperform an O(N log N) algorithm with poor cache locality on small inputs.

Furthermore, worst-case complexity can be misleading if the worst-case trigger is exceptionally rare. In such scenarios, amortized analysis is used to measure the average cost per operation over a long sequence of operations. For example, Python lists double their allocated storage when full; appending an item takes O(1) amortized time even though the rare resizing step takes O(N) time.

Binary search demonstrating logarithmic time complexity O(log N)

def binary_search(sorted_array, target):    # Problem space halves on every iteration -> O(log N) time, O(1) space    left = 0    right = len(sorted_array) - 1        while left <= right:        mid = (left + right) // 2        mid_val = sorted_array[mid]                if mid_val == target:            return mid        elif mid_val < target:            left = mid + 1        else:            right = mid - 1                return -1# A list of 1,000,000 elements requires at most ~20 iterationsitems = list(range(0, 1_000_000, 2))print(binary_search(items, 500_000))

Key takeaways

  • Logarithmic growth O(log N) arises when the input is repeatedly halved at each step.
  • Divide-and-conquer algorithms like merge sort run in O(N log N) time.
  • Amortized time averages expensive periodic operations across sequences of cheap operations.
  • Hardware realities like cache lines and constant factors can dictate performance on small data sizes.

Complexity

  • Time: Best: O(1), Average: O(N), Worst: O(N^2)
  • Space: O(1) auxiliary space

Complexity varies according to the algorithmic approach chosen. Searching an unordered sequence takes O(1) in the best case if the item is at the start and O(N) in the worst case. Nested pairwise comparisons require O(N^2) time because each of the N elements is paired with every other element.

Common mistakes

  • Equating time complexity with exact execution seconds instead of scaling behavior.
  • Assuming two sequential loops automatically produce O(N^2) instead of O(N).
  • Neglecting hidden operations inside built-in library functions, such as 'item in list' being an O(N) search.
  • Forgetting to drop lower-order terms, such as reporting O(N^2 + N) instead of O(N^2).
  • Confusing the number of inputs with different dimensions, such as using O(N^2) instead of O(N * M) when looping over two distinct collections.

Practice problems

  1. Analyze an accumulator loop with early exit (easy). Hint: Count the maximum number of iterations executed if the condition never triggers.
  2. Determine complexity of string duplication (medium). Hint: Remember that creating a new string of length K requires allocating and copying K characters in memory.
  3. Analyze a halving loop inside an incrementing loop (hard). Hint: Multiply the number of outer iterations by the number of times the inner variable can be divided by two.

Summary

Time complexity and Big O notation provide an objective standard to classify algorithmic efficiency as data scales. By abstracting machine-specific constants, developers can classify algorithms into constant, logarithmic, linear, and polynomial classes to select the right algorithm before writing production code.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!