beginnergeneral

Big-O Basics

Big-O Basics

Big-O notation describes how an algorithm's runtime grows as the input size increases. It's the standard language for comparing algorithm efficiency — it tells you how well an algorithm scales.

Why It Matters

Two algorithms might both solve the same problem, but one might take 1 second for 1,000 items while the other takes 1 hour. Big-O helps you predict this before running the code.

Common Complexities

O(1) — Constant Time

The runtime doesn't depend on input size. No matter how large the data, it takes the same time.

O(log n) — Logarithmic

Each step eliminates half the remaining data. Extremely efficient for large inputs.

O(n) — Linear

You look at every element once. Runtime grows directly with input size.

O(n log n) — Linearithmic

The sweet spot for comparison-based sorting. Slightly worse than linear, far better than quadratic.

O(n^2) — Quadratic

Nested loops over the same data. Becomes painfully slow around n = 10,000.

Code Snippets

O(1) — Constant

def get_first_element(items: list) -> any:
    """Access by index — always one operation regardless of list size."""
    return items[0]

O(log n) — Logarithmic

def binary_search(sorted_numbers: list[int], target: int) -> int:
    """Halve the search space each step."""
    left_bound = 0
    right_bound = len(sorted_numbers) - 1

    while left_bound <= right_bound:
        middle_index = (left_bound + right_bound) // 2
        if sorted_numbers[middle_index] == target:
            return middle_index
        elif sorted_numbers[middle_index] < target:
            left_bound = middle_index + 1
        else:
            right_bound = middle_index - 1
    return -1

O(n) — Linear

def find_maximum(numbers: list[int]) -> int:
    """Single pass through all elements."""
    largest = numbers[0]
    for current_number in numbers:
        if current_number > largest:
            largest = current_number
    return largest

O(n log n) — Linearithmic

def merge_sort(numbers: list[int]) -> list[int]:
    """Divide-and-conquer: split, sort halves, merge."""
    if len(numbers) <= 1:
        return numbers

    midpoint = len(numbers) // 2
    left_half = merge_sort(numbers[:midpoint])
    right_half = merge_sort(numbers[midpoint:])
    return merge_halves(left_half, right_half)


def merge_halves(left: list[int], right: list[int]) -> list[int]:
    """Merge two sorted lists into one."""
    merged_result = []
    left_index = 0
    right_index = 0

    while left_index < len(left) and right_index < len(right):
        if left[left_index] <= right[right_index]:
            merged_result.append(left[left_index])
            left_index += 1
        else:
            merged_result.append(right[right_index])
            right_index += 1

    merged_result.extend(left[left_index:])
    merged_result.extend(right[right_index:])
    return merged_result

O(n^2) — Quadratic

def bubble_sort(numbers: list[int]) -> list[int]:
    """Nested loops comparing every adjacent pair."""
    array_length = len(numbers)
    for pass_number in range(array_length):
        for current_index in range(array_length - 1 - pass_number):
            if numbers[current_index] > numbers[current_index + 1]:
                numbers[current_index], numbers[current_index + 1] = (
                    numbers[current_index + 1], numbers[current_index]
                )
    return numbers

How to Identify Complexity

Pattern in CodeComplexity
No loops, direct accessO(1)
Halving the problem each stepO(log n)
Single loop through n itemsO(n)
Divide in half then process each halfO(n log n)
Nested loop over same dataO(n^2)
Three nested loopsO(n^3)
All subsets or permutationsO(2^n) or O(n!)

Practical Rules

  • Drop constants: O(2n) is just O(n)
  • Drop lower-order terms: O(n^2 + n) is just O(n^2)
  • Worst case is what Big-O describes by default
  • Space complexity counts extra memory used (not the input itself)