Skip to content

Big O and the interview method

Big O describes how a cost grows with the input size. It does not predict a runtime in seconds. Before you name a cost, define the input size and the work that you count.

For a list, n usually means its length. For a graph, use V for vertices and E for edges. For two strings, preserve both lengths unless the problem bounds them together. A loop over each string costs O(m + n), not O(m * n).

O(f(n)) gives an eventual upper bound up to a constant factor. In an interview, give the tightest usual bound that your argument supports. A linear algorithm also has a quadratic upper bound, but that description hides useful information. Theta(f(n)) states matching upper and lower bounds. The logarithm base does not change a Big O class because different fixed bases differ by a constant factor.

Cost Typical source of work
O(1) Read a Python list element at a known index.
O(log n) Halve a candidate interval until it is empty.
O(n) Visit every element once.
O(n log n) Sort arbitrary comparable values with a comparison sort.
O(n²) Compare every pair of positions.
O(2ⁿ) Explore the include or exclude decisions for n items.
O(n!) Explore every ordering of n distinct items.

The last two rows count search decisions. Copying every subset adds a factor of n to the total worst-case time. Copying every permutation also adds a factor of n. Count the work at each leaf as well as the number of leaves.

An event log contains integer category codes. Count how many entries match a target and how many pairs of distinct positions contain the same code. The examples below deliberately count comparisons instead of wall-clock time. All integers fit in a fixed number of machine words for this cost model.

def count_matches(values: list[int], target: int) -> tuple[int, int]:
"""Count matching entries and equality comparisons.
Args:
values: Integer category codes.
target: Code to count.
Returns:
The match count and the comparison count.
"""
matches = 0
comparisons = 0
for value in values:
comparisons += 1
if value == target:
matches += 1
return matches, comparisons
def count_equal_pairs(values: list[int]) -> tuple[int, int]:
"""Count equal pairs at distinct positions and comparisons.
Args:
values: Integer category codes.
Returns:
The equal-pair count and the comparison count.
"""
pairs = 0
comparisons = 0
for left in range(len(values)):
for right in range(left + 1, len(values)):
comparisons += 1
if values[left] == values[right]:
pairs += 1
return pairs, comparisons
def count_halvings(size: int) -> int:
"""Count integer halvings until a nonnegative size is at most one.
Args:
size: Initial nonnegative candidate count.
Returns:
The number of halvings.
Raises:
ValueError: If size is negative.
"""
if size < 0:
raise ValueError("size must be nonnegative")
steps = 0
while size > 1:
size //= 2
steps += 1
return steps
codes = [4, 7, 4, 9, 7]
print("Matches and comparisons:", count_matches(codes, 4))
print("Pairs and comparisons:", count_equal_pairs(codes))
print("n | linear comparisons | pair comparisons | halvings")
for size in (4, 8, 16):
values = list(range(size))
print(size, count_matches(values, -1)[1],
count_equal_pairs(values)[1], count_halvings(size), sep=" | ")
Matches and comparisons: (2, 5)
Pairs and comparisons: (2, 10)
n | linear comparisons | pair comparisons | halvings
4 | 4 | 6 | 2
8 | 8 | 28 | 3
16 | 16 | 120 | 4

After each iteration of count_matches, matches equals the number of matching entries in the processed prefix. The loop examines all n entries, so its time is Theta(n) and its auxiliary space is O(1).

The pair loops examine n - 1, then n - 2, down to zero candidate partners. Their sum is n(n - 1) / 2, so the time is Theta(n²). Both loops together use only a fixed number of scalar variables. Their auxiliary space is O(1). The halving loop has Theta(log n) iterations for positive growing n and O(1) auxiliary space.

Claim Meaning Python example
Worst-case cost The cost bounds every valid input of that size. A failed linear search reads all n values.
Expected cost The cost relies on a probabilistic assumption. Dictionary lookup is expected O(1) with suitable hash distribution.
Amortized cost The total cost is spread across a sequence of operations. List append is amortized O(1) despite occasional O(n) growth.

Expected does not mean amortized. A dictionary can encounter collisions, while a list eventually needs a larger array even without adversarial input. State the assumption when an algorithm depends on expected dictionary or set operations. State the worst case when the interviewer asks for it.

values[left:right] creates a list with k selected references. It costs O(k) time and space. A loop that repeatedly copies a growing prefix can therefore cost O(n²) despite one visible for statement.

String concatenation creates new strings. List membership searches element by element. list.pop(0) shifts remaining references. These operations belong in the cost calculation even when each appears on one source line.

Auxiliary space excludes the input and returned output unless you state another convention. A recursive call also occupies a stack frame. If you return all subsets, report both the recursion stack and the space for the returned subsets. For arbitrary-size integers, include the cost of arithmetic on their digits when that growth changes the conclusion.

  1. State the input, output, and assumptions about duplicates, order, and mutation.
  2. Describe a correct direct solution and count its repeated work.
  3. Choose a structure that removes that repeated work.
  4. State an invariant that remains true after each step.
  5. Trace one ordinary input and one boundary input.
  6. Derive time and auxiliary space from the operations in the final code.

For the equal-pair problem, a useful explanation is, “The double loop visits each unordered pair once. A frequency dictionary can count earlier matches without revisiting each earlier position.” The hash-map lesson explains how a dictionary preserves information from a prefix.

assert count_matches([], 4) == (0, 0)
assert count_matches([4], 4) == (1, 1)
assert count_equal_pairs([]) == (0, 0)
assert count_equal_pairs([4, 4, 4]) == (3, 3)
assert count_halvings(0) == 0
assert count_halvings(1) == 0
print("The empty, singleton, and duplicate cases pass.")
The empty, singleton, and duplicate cases pass.

Contains Duplicate lets you compare pairwise checks with a set. Explain both the additional space and the assumption behind constant-time membership.

Binary Search lets you count the remaining candidate positions after each comparison. Explain why halving gives a logarithm rather than division by two as the final complexity.

Download the Python source to run the complete example locally.

MIT’s Python cost model connects Python operations to algorithm analysis. Use it to identify work hidden inside a built-in operation.

Python’s bisection performance notes distinguish a logarithmic search from linear insertion. They explain why the cost of one subroutine does not determine the cost of the complete algorithm.