Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Think like a problem solver
EXPERIMENT 04 / 66

Count the work, not just the seconds.

Reason about growth and compare algorithms before a small timing test misleads you.

BY NAVAN SAMI◷ 8 MIN READSTARTERALGORITHM

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.

THE THING THAT MUST STAY TRUE

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.

the_strategy.txt
FOR each value
  count a comparison
  IF value is target: return found
RETURN not found

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

complexity.py
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))
↳ EXPECTED OUTPUT
(True, 8)
(True, 16)
  1. 1

    The target sits at the end in both examples, exposing a worst-case scan. Doubling the input doubles the number of comparisons.

  2. 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. 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

TIME

O(n) worst-case scan

SPACE

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

A SMALL MISSION

Count the number of pairs produced by a nested n-by-n loop for n=4 and n=8.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

How does an n-by-n nested loop normally grow?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.