Understanding Big O notation from operational counting to asymptotic limits
Learn how to calculate and communicate algorithmic efficiency using Big O notation, from manual operation counting to rigorous upper-bound reasoning.
MonksBit Desk
November 26, 2026 · 9 min read · 75 views
Read
Big O notation is a mathematical framework used in computer science to classify algorithms according to how their run time or memory requirements grow as the input size grows. It describes an asymptotic upper bound on the growth rate of a function, allowing developers to compare efficiency independently of machine hardware or programming languages.
You will need. Basic programming concepts such as variables, loops, and functions · Familiarity with Python syntax
The full lesson
Level 1 · Beginner: Counting operations and observing growth curves
To measure how efficient an algorithm is, we do not measure execution time in seconds. Wall-clock time varies across different computers, background processes, and programming language runtimes. Instead, we measure the number of primitive operations an algorithm executes relative to the size of the input, conventionally designated by the variable n.
Consider a list of numbers with size n. If an algorithm checks the first element and immediately returns it, that operation takes one step whether n is five or five million. This behavior is called constant time, written in Big O notation as O(1). If an algorithm loops over all n elements to sum them up, it performs roughly one addition per item, requiring n steps. This is linear time, written as O(n).
When evaluating an algorithm by hand, trace its execution on a tiny input. For an input list of three items [4, 7, 2], finding the sum requires stepping through 4, then 7, then 2. That is three loop iterations. For four items, it takes four iterations. The number of basic steps grows in direct proportion to the number of items.
The following code demonstrates these two fundamental behaviors: accessing a specific element in constant time O(1), and traversing an entire list in linear time O(n).
Demonstration of constant time O(1) and linear time O(n) functions
def get_first_item(items): if not items: return None return items[0]def calculate_sum(items): total = 0 for item in items: total += item return totalsample_data = [10, 20, 30, 40, 50]print(get_first_item(sample_data))print(calculate_sum(sample_data))
Key takeaways
- Big O measures how step counts scale with input size n, not elapsed wall-clock seconds.
- O(1) signifies constant time, meaning the execution steps do not change with input size.
- O(n) signifies linear time, meaning the execution steps scale in direct proportion to input size.
Level 2 · Intermediate: Rules of simplification, nested loops, and memory scaling
Real-world algorithms often execute combinations of sequential and nested operations. To express these algorithms concisely, Big O notation applies two fundamental simplification rules: drop constant factors, and drop lower-order terms. For example, if an algorithm executes 5n + 12 steps, we simplify this expression to O(n) because as n reaches billions, the multiplier 5 and the constant offset 12 become insignificant compared to the overall rate of growth.
Nested loops generally cause growth rates to multiply. If an outer loop runs n times and an inner loop runs n times for every single iteration of the outer loop, the inner body runs n multiplied by n times, which is n squared. We express this quadratic growth as O(n^2). Conversely, loops that execute sequentially rather than nested inside each other are additive: a loop running n times followed by another loop running n times yields 2n operations, which simplifies to O(n).
Input data can also vary beyond a single dimension. When a function processes two distinct collections of lengths a and b, the complexity must reflect both independent variables, yielding O(a + b) for sequential iteration or O(a * b) for nested iterations. Collapsing distinct variables into a single n prematurely obscures true algorithmic costs.
Big O applies equally to memory consumption, known as space complexity. Auxiliary space measures the extra memory an algorithm allocates beyond the input data itself. Storing intermediate results in a list of size n requires O(n) extra space, whereas tracking a running total using a single counter requires O(1) auxiliary space.
The accompanying example demonstrates nested iteration that detects duplicate elements, contrasting quadratic time complexity with linear auxiliary space.
Quadratic pair-checking algorithm compared with linear set tracking
def contains_duplicates_nested(items): length = len(items) for i in range(length): for j in range(i + 1, length): if items[i] == items[j]: return True return Falsedef contains_duplicates_set(items): seen = set() for item in items: if item in seen: return True seen.add(item) return Falsenumbers = [1, 3, 5, 7, 3]print(contains_duplicates_nested(numbers))print(contains_duplicates_set(numbers))
Key takeaways
- Ignore constant coefficients and lower-order terms to focus exclusively on asymptotic growth.
- Nested iterations multiply complexities, whereas sequential blocks add together.
- Distinct input dimensions must remain separate variables such as O(a * b).
- Space complexity measures auxiliary memory growth alongside time complexity.
Level 3 · Advanced: Formal asymptotic bounds, amortisation, and practical limits
Formally, Big O defines an asymptotic upper bound. A function f(n) is in O(g(n)) if there exist positive constants c and n0 such that f(n) <= c * g(n) for all n >= n0. Two companion notations complete the standard hierarchy: Big Omega denotes an asymptotic lower bound indicating the best-case work, while Big Theta denotes an asymptotically tight bound where the upper and lower bounds match within constant factors.
Algorithms often exhibit different complexities depending on input distribution. For instance, linear search terminates in one step if the target is at index zero, achieving best-case O(1) time, but requires O(n) steps if the target is absent, yielding worst-case O(n) time. Unless qualified otherwise, software engineering discussions refer to worst-case behavior to guarantee performance boundaries.
Some operations vary periodically in cost rather than staying uniform. Dynamic arrays such as Python lists append items in O(1) time on average, but periodically trigger an O(n) reallocation and copy when capacity is exhausted. Amortised analysis averages the cumulative cost of a sequence of operations over time, proving that n consecutive append operations take O(n) total time, which yields an amortised cost of O(1) per operation.
Big O has practical limitations in production engineering. It intentionally ignores constant factors and cache locality. An algorithm with O(n) complexity that incurs frequent cache misses or expensive constant-factor math may run slower on small or medium datasets than an O(n log n) or O(n^2) algorithm with contiguous memory access and negligible constants. Asymptotic dominance only guarantees superior speed once n exceeds a threshold.
Simulating amortised dynamic array growth and tracking resize overhead
class ResizableArray: def __init__(self): self.capacity = 1 self.size = 0 self.storage = [None] * self.capacity self.total_copies = 0 def append(self, value): if self.size == self.capacity: new_capacity = self.capacity * 2 new_storage = [None] * new_capacity for i in range(self.size): new_storage[i] = self.storage[i] self.total_copies += 1 self.storage = new_storage self.capacity = new_capacity self.storage[self.size] = value self.size += 1array = ResizableArray()for value in range(1000): array.append(value)print(f"Total items: {array.size}")print(f"Total internal copy steps: {array.total_copies}")print(f"Average copy steps per append: {array.total_copies / array.size:.2f}")
Key takeaways
- Big O is an upper bound, Big Omega is a lower bound, and Big Theta is a tight bound.
- Amortised complexity guarantees the average cost per operation across worst-case sequences.
- Hardware realities like cache lines and constant factors can dominate over pure Big O for small inputs.
Complexity
- Time: O(1) best case, O(n^2) worst case depending on the comparison pattern
- Space: O(1) auxiliary space for nested traversal, O(n) auxiliary space for hash-set tracking
Nested pair-checking compares each index against subsequent elements, resulting in n*(n-1)/2 comparisons, which simplifies to O(n^2) time with O(1) space. The hash set implementation reduces time to O(n) by checking lookup tables in constant expected time at the expense of O(n) allocated memory.
Common mistakes
- Equating Big O directly with wall-clock time in milliseconds rather than operation counts relative to input size.
- Retaining constant factors or lower-order components, such as writing O(3n + 4) instead of O(n).
- Collapsing multiple distinct inputs into one variable, such as writing O(n^2) instead of O(n * m) for grids of dimensions n and m.
- Confusing worst-case runtime with average-case or amortised runtime without stating assumptions.
- Neglecting space complexity by only measuring loop execution times while ignoring allocated collections.
Practice problems
- Single loop step counting (easy). Hint: Count how many times the loop body executes if the loop index increments by 2 each iteration instead of 1.
- Two-variable matrix scan (medium). Hint: Express the time complexity in terms of both row count r and column count c when iterating over a non-square matrix.
- Amortised accounting for a custom bounded stack (hard). Hint: Determine the aggregate cost of n push and pop operations when a resize occurs every power of two.
Summary
Big O notation provides a hardware-independent language for evaluating the scalability of algorithms. By learning to count dominant operations, simplify algebraic terms, account for multi-variable inputs, and balance space against time, engineers can design predictable, production-grade systems.
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!