Count the work, not just the seconds.
Reason about growth and compare algorithms before a small timing test misleads you.
01 Model the idea
Complexity describes how resource use grows with input size. Big O expresses an upper growth bound, usually ignoring constant factors. Looking up an item in a hash set is expected constant time, while scanning a list is linear in its length. These are models under assumptions, not guarantees that one tiny program always runs faster on every machine.
Every examined position has either matched or been ruled out.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
FOR each value
count a comparison
IF value is target: return found
RETURN not found03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def scan(values, target):
checks = 0
for value in values:
checks += 1
if value == target:
return True, checks
return False, checks
print(scan(list(range(8)), 7))
print(scan(list(range(16)), 15))(True, 8) (True, 16)
- 1
The target sits at the end in both examples, exposing a worst-case scan. Doubling the input doubles the number of comparisons.
- 2
A scan can finish after one comparison in the best case. State whether your complexity claim concerns best, average, expected, amortised, or worst-case behaviour.
- 3
Space complexity counts extra storage as well. Building a set can make repeated queries faster but costs memory and construction work; that trade-off may be worthwhile only for multiple queries.
04 Count the cost
O(n) worst-case scan
O(1) auxiliary
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Count the number of pairs produced by a nested n-by-n loop for n=4 and n=8.
Reveal one possible solution +
def pairs(n):
count = 0
for _ in range(n):
for _ in range(n): count += 1
return count
print(pairs(4), pairs(8))06 Check your reasoning
How does an n-by-n nested loop normally grow?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.