Time complexity
Time complexity describes how the number of steps in an algorithm grows as the input gets larger. Big O names the dominant term: O(1), O(n), O(n log n), O(n²), and so on.
Detailed Explanation
A function that walks a list once does work proportional to the length of the list. We say it is O(n). Doubling the list roughly doubles the time. A nested loop over the same list is O(n²): doubling the list roughly quadruples the time. Big O ignores constants and slower-growing terms. 3n + 12 is O(n). n² + 100n is O(n²). The point is the shape of the curve, not a millisecond count.
You measure steps, not wall time. A Python for loop has a large constant next to a C loop. O(n) in Python can lose to O(n log n) in C on medium n. Complexity still tells you which algorithm wins as n grows, and which operations you cannot afford on a list of a million.
Python's builtins have known costs. List index and append (amortised) are O(1). List insert at 0 is O(n). Dict and set average O(1) lookup, worst-case O(n) if hashing collapses. Sorting is O(n log n). x in list is O(n). x in set is O(1) average. Replacing a scan with a set is the most common interview (and production) win.
Amortised cost matters. list.append is O(1) on average because occasional resizes of O(n) are rare. A single append can be slow; n appends are linear.
Worst case, average case, and best case are different claims. Quicksort is O(n log n) average and O(n²) worst. Hash lookup is O(1) average and O(n) worst. Say which one you mean when the difference is a security or latency issue.
Complexity is not a substitute for measurement. Profile the real input. Then use Big O to explain the profile and to choose a structure before you write the loop.
Code Examples
# O(n): one pass.
def total(cents: list[int]) -> int:
acc = 0
for value in cents: # n iterations
acc += value
return acc
# O(n²): nested pass over the same data.
def has_pair(cents: list[int], target: int) -> bool:
for i, left in enumerate(cents):
for right in cents[i + 1 :]:
if left + right == target:
return True
return False# Same question, O(n) with a set.
def has_pair_fast(cents: list[int], target: int) -> bool:
seen: set[int] = set()
for value in cents:
if target - value in seen: # O(1) average
return True
seen.add(value)
return False
print(has_pair_fast([1, 4, 9], 13)) # TrueCommon Gotchas
`x in list` inside a loop is O(n²)
build a set once.
Big O hides constants
an O(n) Python loop can lose to O(n log n) in C on your real n. Measure.
Worst case on dicts is rare but real
pathological hashes or many collisions degrade to linear. Do not treat O(1) as a hard cap in adversarial settings.
Recursion depth is not time complexity
a linear recursive function is O(n) time and O(n) stack. Both matter.