Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 17 / Topic 1 of 20

Big-O notation

Big-O is a way to describe how an algorithm's work grows as its input grows, ignoring machine speed and small constants. It answers "if my input doubles, does my program get a bit slower, twice as slow, or four times as slow?" Think of packing: packing one more shirt into a half-empty suitcase costs almost nothing extra, but packing one more shirt into an already-overflowing warehouse of shirts (where you first have to find space) costs more and more as the warehouse fills up. Big-O describes that growth pattern, not the exact seconds.

Class Name Growing input means... Example
O(1) constant time barely changes dict["key"], list[i], stack.append(x)
O(log n) logarithmic time grows very slowly binary search, balanced tree lookup
O(n) linear time grows in step with input scanning a list once
O(n log n) linearithmic a bit worse than linear sorted(), merge sort
O(n²) quadratic time grows with the SQUARE of input nested loop over the same list
O(2ⁿ) exponential time roughly doubles per extra item naive recursion with no memory of past answers

The only honest way to know an algorithm's real-world speed is to measure it, the same golden rule as Part 14. Here is the same bug - "does this list contain a duplicate?" - solved an O(n²) way (compare every pair) and an O(n) way (remember what you have seen in a set), timed with time.perf_counter as the input grows:

import time

def has_duplicate_slow(items):                 # O(n^2): compares every pair
    for i in range(len(items)):
        for j in range(i + 1, len(items)):
            if items[i] == items[j]:
                return True
    return False

def has_duplicate_fast(items):                  # O(n): one pass, a set remembers
    seen = set()
    for x in items:
        if x in seen:
            return True
        seen.add(x)
    return False

Timed on worst-case input (no duplicate, so both functions must look at everything):

     n |  O(n^2) slow |    O(n) fast
  1000 |       7.0 ms |     0.016 ms
  2000 |      27.4 ms |     0.029 ms
  4000 |     116.8 ms |     0.056 ms   (varies by machine)

Doubling n roughly quadruples the O(n²) time (27.4 → 116.8, about 4x) but barely more than doubles the O(n) time. That ratio - not the exact milliseconds - is what Big-O predicts, and it is why an O(n²) solution that feels "fine" on 1,000 test rows can time out on 1,000,000 real rows.

Real-world example: a sign-up form checks "is this phone number already registered?" against a growing list of users. With 1,000 users an O(n²)-style list scan feels instant; with 2,000,000 users (a real app's user base) the same list scan becomes a visible delay on every sign-up, while a set lookup stays just as fast as it was at 1,000.

⚠️ Big-O describes growth, not an exact time. An O(n) algorithm can still be slower than an O(n²) one for a tiny n, because Big-O drops constant factors. It matters once n gets large - which, for real apps, it eventually does.

Practice: work out the Big-O of a few snippets by hand before running them; rewrite a brute-force "any duplicates?" or "any pair matching X?" checker to use a set instead of a nested loop; time your own before/after with time.perf_counter, the way Part 14 taught.

Practice on LeetCode - start here: Contains Duplicate · Valid Anagram · Intersection of Two Arrays

Show the full practice list (4 more problems)

Core practice - gentler first:

Full program: examples/01_big_o_timing.py.

Exercise 1: Big-O — measure, don't guess

Scenario: A cashier app checks "has this UPI ID already paid today?" against a growing list of payments. You want proof, not a guess, that a set beats a list as the list grows. What to do: Inside main():

  1. Write seen_in_list(paid, upi_id) (return upi_id in paid, where paid is a list) and seen_in_set(paid, upi_id) (same check on a set).
  2. Build paid_list = [f"user{n}@upi" for n in range(20_000)] and paid_set = set(paid_list).
  3. Using time.perf_counter(), time 1,000 calls to seen_in_list(paid_list, "user19999@upi") (the worst case: last item) and 1,000 calls to seen_in_set(paid_set, "user19999@upi").
  4. Print both totals in milliseconds, and print whether the set was faster.

Sample output:

list total: 83.4 ms
set total: 0.07 ms
Set was faster: True
Show the solution to Exercise 1
"""Exercise 1: Big-O - measure, don't guess.

Run:   python ex01.py   (macOS/Linux: python3 ex01.py)
"""

import time


def seen_in_list(paid: list[str], upi_id: str) -> bool:
    return upi_id in paid


def seen_in_set(paid: set[str], upi_id: str) -> bool:
    return upi_id in paid


def main() -> None:
    paid_list = [f"user{n}@upi" for n in range(20_000)]
    paid_set = set(paid_list)
    target = "user19999@upi"          # last item: worst case for the list

    start = time.perf_counter()
    for _ in range(1_000):
        seen_in_list(paid_list, target)
    list_total = (time.perf_counter() - start) * 1000

    start = time.perf_counter()
    for _ in range(1_000):
        seen_in_set(paid_set, target)
    set_total = (time.perf_counter() - start) * 1000

    print(f"list total: {list_total:.1f} ms")
    print(f"set total: {set_total:.2f} ms")
    print(f"Set was faster: {set_total < list_total}")


if __name__ == "__main__":
    main()

💡 Hint: Wrap each block of 1,000 calls in a for _ in range(1_000): loop between two time.perf_counter() reads.

Search the guide