Week 3: Complexity Analysis

Computer Algorithms (506994-002)

Ridho Hendra, Ph.D · Dept. of Intelligent Computing · Mon [1-3] · Building A, Room 703
Assignment 1 released this week - due Week 5
Department of Intelligent Computing

Where We Are

Wk 1
Introduction
Wk 2
Algorithm Concepts
Wk 3
Complexity Analysis
Wk 4
Recursion & Recurrence
Wk 5
Basic Sorting
Wk 6
Advanced Sorting
Wk 7
Searching
Wk 8
Midterm Exam
Wk 9
Divide & Conquer
Wk 10
Greedy Algorithms
Wk 11
Dynamic Programming I
Wk 12
Dynamic Programming II
Wk 13
Graph Representation
Wk 14
Shortest Path
Wk 15
Final Exam
Department of Intelligent Computing

Two Functions, One Race

A crossover point, resolved directly - no formulas required yet.

Two algorithms exist for the same problem. Algorithm A costs about
steps. Algorithm B costs about steps.

  • At : A costs 10,000 steps. B costs 100 steps - B wins by 100x.
  • At : A costs 2,000,000 steps. B costs 4,000,000 steps -
    the ranking flips: A is now half the cost of B.

Somewhere between and sits a crossover point (it's
exactly , where ) where the winner changes.
"Algorithm B is faster" is not yet a well-defined claim until we say
for which - which is exactly what today's tools fix: a way to
compare growth rates that doesn't depend on picking one favorite .

Department of Intelligent Computing

Last Week, This Week

  • Last week delivered: CampusNav's FIND_ROOM now exists as real, checkable pseudocode - verified against all five required properties (finiteness, definiteness, input, output, effectiveness).
  • Last week left broken: we can now write two different correct algorithms for the same problem, but we still have no rigorous way to say which one is actually better - "better" is still just a feeling.
Department of Intelligent Computing

Key Words Today

  • Time complexity: how an algorithm's running cost grows as input size grows.
  • Space complexity: how much extra memory an algorithm needs, as a function of input size.
  • Asymptotic: describing behavior as gets arbitrarily large - not at one fixed size.
  • Tight bound: a growth-rate claim that is neither an exaggeration nor an underestimate - formalized today as .
Department of Intelligent Computing

Two Correct Answers, One Argument

Two students both submit pseudocode for CampusNav's "find room
703 in Building A" feature. Both pass every test the TA (teaching assistant) throws at them - every
single time, the correct room comes back. In the study group, one
student swears their version is "obviously faster." The other says
"prove it." Neither can point to anything beyond a stopwatch and a
shrug, and neither can say what happens once the directory has ten
times as many rooms in it. Nobody in the room has a rule for settling
the argument.

Department of Intelligent Computing

Both Work. Only One Might Scale.

One building, ~40 rooms
both feel instant
Whole campus, ~1,200 rooms
one starts to lag
Campus + partner campuses, 10,000+ rooms
nobody can predict this - yet
Illustrative, not measured data: the point is that "it worked on my test" says nothing about the third row.
Department of Intelligent Computing

What Not Knowing Actually Costs

  • Two correct solutions can differ by orders of magnitude in cost, but without a rigorous measure, the CampusNav team can't predict that difference before it hurts users.
  • Nobody can promise "this will still be fast" once the directory grows - only guess.
  • Every design decision (which data structure, which loop shape) becomes a debate settled by opinion instead of proof.
Department of Intelligent Computing

What Not Knowing Actually Costs, In Industry

In industry: "What's the time complexity of your solution?" is the single most common follow-up question in a technical interview - and a wrong answer, or no answer, fails candidates who wrote perfectly correct code.
Department of Intelligent Computing

It Gets Worse As the Problem Grows

Small test input
every method looks fine
Real production data
gaps start to show
Data grows 10-100x (the norm, not the exception)
the wrong choice becomes unusable
Illustrative, not measured data: the point is the trend, not the exact percentages.

A system with no plan for this will ship a feature that quietly
stops working the moment it succeeds and gains more users or data.

Department of Intelligent Computing

This Week's Question

"How do we precisely measure an algorithm's cost, and predict - not guess - how that cost grows as CampusNav's data grows?"
Department of Intelligent Computing

By the End of This Week, You Can

  1. State the formal definition of Big-O notation and prove a growth-rate bound directly from it, exhibiting valid constants and .
  2. Order the common growth rates from slowest- to fastest-growing, and identify which term dominates a bound.
  3. Distinguish time complexity from space complexity, and distinguish a growth-rate bound from a single measured running time.
  4. Analyze how CampusNav's current linear-scan room lookup will behave as the directory grows from 1,200 to 10,000+ entries.
Department of Intelligent Computing

Assignment 1: Released Today

Everything from this week, applied on paper.
  • Assignment 1 - Complexity & Pseudocode is out starting today.
  • Three parts: CLRS-style (Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms, 4th ed) pseudocode, Big-O proofs, and a growth-rate ordering exercise.
  • Due Week 5, 23:59, submitted individually via the course Learning Management System (LMS).
  • Full spec, rubric, and submission format: materials/assignments/assignment1.md
  • Separate from this week's own short Week 3 Check (see the Summary slide) - both are active this week, but they cover different work.
Department of Intelligent Computing

This Problem Is Not New Either

Different course, same field: mathematicians hit this exact wall a century before computers existed.
1894
Paul Bachmann introduces O-notation in a number theory book, to describe error-term bounds cleanly.
1909
Edmund Landau popularizes and formalizes it - this family is still called "Landau notation."
1976
Donald Knuth adapts O, Ω, Θ specifically for algorithm analysis, standardizing what this course uses today.
Computer scientists needed exactly what mathematicians needed: a way to compare two formulas' growth without caring about one specific machine, compiler, or lucky benchmark run.
Department of Intelligent Computing

A Motivating Example: Racing Two Real Features

Back to the warm-up - now with an actual CampusNav feature.

CampusNav's room directory is scraped from campus signage, and a few
rooms end up listed twice by mistake. CampusNav wants a "find duplicate
entries" feature. One design compares every pair of entries; another
design is smarter.

Directory size () Naive pairwise check Linear scan (for comparison)
40 1,600 comparisons 40 steps
1,200 1,440,000 comparisons 1,200 steps
10,000 100,000,000 comparisons 10,000 steps

Same correctness, wildly different cost - and the gap widens, not
narrows, as grows. We need a name for that shape of growth.

Department of Intelligent Computing

Big-O: Formal Definition

One line of math, and today's entire vocabulary becomes precise (CLRS 4th ed, Ch 3).

if and only if there exist positive constants
and such that for all .

In plain words: never grows faster than some constant multiple
of , once is large enough. is an upper bound
on growth rate - not a running time.

Department of Intelligent Computing

Key Words Today

  • Constants (, ): the proof only needs some values to exist - you get to choose them, and they don't need to be small or "nice."
  • Dominant term: the single term in a formula that grows fastest - the only one that survives inside Big-O.
  • Big-Ω, Big-Θ: the matching lower-bound and tight-bound notations, defined the same way as Big-O (next slide).
  • In-place: an algorithm that uses no extra memory beyond a constant amount, regardless of (today's space-complexity idea).
Department of Intelligent Computing

Reading the Definition, Piece by Piece

1
Pick a comparison function $g(n)$ - usually the simplest shape that matches $f$'s growth (e.g. $n^2$).
2
Find any constant $c > 0$ that, once multiplied by $g(n)$, stays on top of $f(n)$. The exact value of $c$ never matters - only that one exists.
3
Find any threshold $n_0$. You are allowed to ignore small, "weird" values of $n$ - the bound only has to hold from $n_0$ onward.
4
If such $c$ and $n_0$ exist, $f(n)$ grows no faster than $g(n)$'s shape, for large $n$. That is the entire promise - nothing about small $n$, nothing about exact seconds.
Department of Intelligent Computing
Big-O proofs · worked example 1 of 3 (simple)

One Failed Attempt, One Valid Proof:

Claim: $f(n) = O(n)$. Not every $(c, n_0)$ attempt works - but only one needs to.
GoalSee a failed constant choice and a valid one, side by side.
1
Try c=5, n0=1
At n=1: f(1)=5(1)+2=7. c·g(1)=5(1)=5. 7 ≤ 5 is false - this pair fails.
→
2
Try c=7, n0=1
At n=1: 7 ≤ 7 holds. For all n≥1: 5n+2 ≤ 5n+2n = 7n, since n≥1 ⇒ 2 ≤ 2n.
→
3
Conclusion
c=7, n0=1 proves f(n)=O(n). The failed attempt above didn't disprove the claim - it only ruled out one pair.
✓
Conclusion5n+2 = O(n), proven with c=7, n0=1.
💡
Key takeawayA failed (c, n0) attempt never refutes a Big-O claim - the definition only requires that some pair exists.
Department of Intelligent Computing
Big-O proofs · worked example 2 of 3 (moderate)

The Full Proof:

The exact proof style Assignment 1 expects - not just the answer, the argument.
GoalProve 3n²+10n+7 = O(n²), then check it numerically.
1
Pick g(n)
g(n) = n². For n≥1: n ≤ n², so 10n ≤ 10n². Also 1 ≤ n², so 7 ≤ 7n².
→
2
Combine
Adding: 3n²+10n+7 ≤ 3n²+10n²+7n² = 20n², for all n≥1. Choose c=20, n0=1.
→
3
Check numerically
n=1: 20≤20. n=2: 39≤80. n=10: 407≤2,000. Holds every time.
→
4
A tighter pair also works
For n≥10: 10n≤n² and 7≤n², so 3n²+10n+7 ≤ 5n² - c=5, n0=10 is an equally valid, tighter proof.
✓
Conclusion3n²+10n+7 = O(n²), proven two different valid ways.
💡
Key takeawayThere is no single "correct" (c, n0) pair - Big-O only asks that some pair exists, which is why two students can turn in different-looking, equally correct proofs of the same bound.
Department of Intelligent Computing
Big-O proofs · worked example 3 of 3 (harder)

A Tight Bound, Both Directions:

O alone was the last two proofs. A Θ claim needs both an upper and a lower bound.
GoalProve n(n−1)/2 = Θ(n²) - this is exactly insertion sort's worst-case comparison count, formalized properly in Week 5.
1
Upper bound (O)
n(n−1)/2 = (n²−n)/2 ≤ n²/2 for all n≥1 (dropping −n only makes it larger). c=½, n0=1.
→
2
Lower bound (Ω)
For n≥2: n−1 ≥ n/2, so n(n−1)/2 ≥ n·(n/2)/2 = n²/4. c=¼, n0=2.
→
3
Conclusion
Both O and Ω hold, so n(n−1)/2 = Θ(n²) - a tight bound, not just an upper one.
★
Why it matters later
This exact formula returns by name in Week 5 as insertion sort's worst-case comparison count - the proof you just did will not need to be redone.
✓
Conclusionn(n−1)/2 = Θ(n²), proven both directions.
💡
Key takeawayΘ is the strongest claim: it says a formula's growth is neither an overestimate nor an underestimate - not just "no worse than."
Department of Intelligent Computing

Big-Ω and Big-Θ: The Other Two Bounds

O is only half the picture - here's the rest of the family.
Notation Meaning Formal definition
Upper bound - "no worse than" for
Lower bound - "no better than" for
Tight bound - "exactly this shape" and

In practice: linear search on a random target is - it
is never faster than proportional to (no shortcut exists) and
never slower either. Most of this course states bounds with , but
is the stronger, more informative claim when it holds.

Department of Intelligent Computing

Math Background You Need Today

Two building blocks show up in every growth rate from here on. Let's ground them first.
  • Logarithm (): "how many times do you halve before you
    reach 1?" , because takes 3
    halvings. This is exactly the shape Week 7's binary search runs on -
    repeatedly cutting a search space in half.
8 3
16 4
1,000 ~10
1,000,000 ~20
Department of Intelligent Computing

Math Background, Continued

One more shape, and two symbols you're about to meet.
  • Unless stated otherwise, "" in this course always means
    - the base rarely matters for Big-O anyway, since
    different bases only differ by a constant factor.
  • Factorial (): multiply every positive integer up to .
    . It shows up whenever an
    algorithm considers every possible ordering of items.
  • ("there exists"): reads like plain English -
    "" means "there exists some constant " - you
    only need to produce one, not find every one.
  • ("grows strictly slower than"): means
    's growth rate stays strictly below 's once is large
    enough - the exact symbol the next slide uses to rank every growth
    rate in this course.
Department of Intelligent Computing

The Growth-Rate Hierarchy

Every algorithm this semester lands on this one line, slowest to fastest.

O(1) ≺
O(log n) ≺
O(√n) ≺
O(n) ≺
O(n log n) ≺
O(n) ≺
O(n²) ≺
O(n³) ≺
O(2ⁿ) ≺
O(n!)

  • Polynomial ( through and beyond): tractable - cost grows, but manageably.
  • Exponential and factorial (, ): intractable at any real scale - shown next.
Department of Intelligent Computing
Growth-rate hierarchy · worked example

Placing Two Growth Rates Precisely

The hierarchy above is an ordering, not a promise about any one input size.
GoalCheck a tempting claim, then place √n and n1.5 exactly.
1
Claim to check
"An O(n1.5) algorithm always runs slower, on every input, than an O(n log n) one." False - Big-O is an asymptotic growth-rate claim, not a promise about every individual input or actual constants.
→
2
Placing √n
Sits strictly between O(log n) and O(n): grows faster than any logarithm, slower than linear - the halfway point between O(1) and O(n) on a log scale.
→
3
Placing n1.5
n1.5 = n·√n: grows faster than n log n, but slower than n².
★
Why the claim is false
A well-tuned O(n1.5) implementation can beat a poorly-tuned O(n log n) one for many realistic sizes of n, even though n1.5 eventually overtakes it once n is large enough.
✓
Conclusion√n and n1.5 both have one exact place in the hierarchy - but neither placement predicts every individual race.
💡
Key takeawayBig-O ranks growth, not literal speed at any one n - the ranking only becomes reliable once n is "large enough," exactly what n0 captures.
Department of Intelligent Computing

Growth Rates, With Real Numbers

Growth rate
1 1 1
~3 ~7 ~10
10 100 1,000
~33 ~664 ~9,970
100 10,000 1,000,000
1,000 1,000,000 1,000,000,000
1,024 ~ unimaginably large
~3,628,800 ~ incomprehensibly large
Department of Intelligent Computing

What "Uncomputable" Actually Means

One row of that table, taken seriously.
At n=10, even O(n!) finishes in well under a second. At n=100, O(2^n) alone is already ≈1.27×10^30 steps - at one billion steps/second, that's roughly 4×10^13 years, about 3,000 times the current age of the universe.
Department of Intelligent Computing

Space Complexity

Cost isn't only time - it's also memory, using the exact same machinery.
  • Space complexity: the extra memory an algorithm uses, as a function of , beyond the input it was given.
  • In-place: uses only extra memory - a fixed number of extra variables, regardless of how large gets. Example: swapping two entries of an array using one temporary variable.
  • Not in-place: allocates a second structure that grows with . Example: CampusNav copying its entire directory into a new array before sorting it - that copy is extra space, regardless of how efficient the sort itself is.
  • Space complexity uses the exact same // machinery as time - just measuring memory instead of steps. "In-place" does not mean zero extra memory, only a fixed amount that doesn't grow with .
Preview: Weeks 5-6 compare sorting algorithms that are provably correct and O(n log n) in time, yet differ sharply in space - some sort in-place, some don't.
Department of Intelligent Computing
CampusNav · timing two real features

The Bill Comes Due: Two Features, Same Directory

Assume one comparison (array access + string check) costs about 50 nanoseconds on typical hardware.
GoalTurn Big-O into an actual clock reading for CampusNav's real directory sizes.
1
Linear scan @ 1,200
CampusNav's actual `FIND_ROOM`, O(n): 1,200 steps × 50ns = 0.06 ms.
→
2
Linear scan @ 10,000+
10,000 steps × 50ns = 0.5 ms. O(n) alone is not the danger here - even 10,000 rooms is imperceptible.
→
3
Duplicate-check @ 1,200
The naive pairwise design, O(n²): 1,440,000 comparisons × 50ns = 72 ms - noticeable.
★
Duplicate-check @ 10,000+
100,000,000 comparisons × 50ns = 5 seconds - the app freezes. "Just add one more feature" is not free: any feature comparing every pair defaults to O(n²).
✓
ConclusionSame directory, same hardware assumption - one feature stays instant at any real size, the other freezes the app.
💡
Key takeawayA 10× growth in n scales O(n) cost about 10×, but scales O(n²) cost about 100× - exactly the jump from 72 ms to 5 seconds above.
Department of Intelligent Computing

Common Mistakes

  • "Big-O tells you the exact running time." Tempting because looks like it should predict a stopwatch reading - but it only bounds how cost grows, never the actual seconds. Two algorithms can differ by a huge constant factor and both be correctly labeled .
  • "Keep the fanciest term you just learned." For , it is tempting to report because that term feels more sophisticated - but for large , grows faster and eventually dwarfs completely. The bound must always come from the fastest-growing term present, never the most recently introduced one.
Department of Intelligent Computing

Key Words Today

  • Recursion: an algorithm defined partly in terms of itself, on a smaller input - previewed next week.
  • Recurrence relation: a formula for cost that is partly written in terms of its own cost - Week 4's entire subject.
  • Divide-and-conquer: a paradigm that splits a problem into smaller independent subproblems - Week 9, once recurrences can be solved.
  • NP-hard: a problem class with no known efficient algorithm at all - Week 14's teaser, and the final destination of "how efficient can this possibly be?"
Department of Intelligent Computing

Why This Shows Up in Interviews, Too

Not only a CampusNav problem.

"State the time complexity of your solution, and prove it" appears in
essentially every technical interview at every major tech company -
not as a formality, but because it is the fastest way to tell whether
a candidate's "working" code will survive contact with real,
large-scale data.

Every course after this one - sorting, searching, databases, machine learning, systems - assumes you can read an algorithm and state its growth rate on sight, the same way this course assumed you could already write a loop.
Department of Intelligent Computing

What Big-O Still Cannot Do

We can now precisely compare any two algorithms' growth rates, and prove those bounds directly from the formal definition - the argument from this morning's warm-up is finally settled with proof, not a shrug. But not every algorithm's cost is a simple, already-known formula in n. An algorithm that calls itself hides its own cost inside a formula that refers back to itself - and we don't yet have a way to solve that kind of formula down to a clean Big-O bound.
Department of Intelligent Computing

Next Week

Week 3 leaves the cost of self-referential algorithms unsolved -
we can bound , but not yet a formula like that refers to itself. Week 4, Recursion & Recurrence,
gives us the tool: recurrence relations, and how to solve them down
to the same Big-O bounds learned today.

Department of Intelligent Computing

Where This Week Lives in CLRS

This week's ideas, mapped to the textbook.
This week's topic CLRS 4th ed
, , - informal and formal definitions §3.1-3.2
Standard notations and common functions (growth-rate hierarchy) §3.3

If you want to go deeper: §3.2's formal definitions extend to
(little-o) and (little-omega) - strict versions of
and that this course doesn't require, but that sharpen the
same idea; CLRS's own end-of-chapter problems are good extra proof
practice beyond Assignment 1.

Department of Intelligent Computing

Summary

  • / / formalize "how cost grows," never "how
    many seconds" - reuse the definition to prove it, not guess it.
  • The fastest-growing term always wins: is ,
    and is , not .
  • An algorithm fine at can be uncomputable at if its
    growth rate is exponential or worse - a structural gap, not a
    matter of a faster computer.
  • CampusNav's core lookup stays -safe at 10,000+ rooms, but any
    feature defaulting to (like naive duplicate-checking) will not.
Department of Intelligent Computing

Summary, Continued

  • New: Week 3 Check - a short graded exercise on Big-O proofs and
    growth-rate placement, released now, due before Week 4 begins - kept
    deliberately separate from Assignment 1, which is also active this
    week (see materials/assignments/week03-check.html).
  • Reading: CLRS 4th ed, Ch 3 (Growth of Functions).
  • Prepare: think about an algorithm that calls itself - how would
    you write its cost as a formula in ? Bring an idea to Week 4.
  • Reminder: Assignment 1 is due Week 5, 23:59.
Department of Intelligent Computing

Thank You

Department of Intelligent Computing

SLOT 1: Title

notes: Welcome the class. Frame the hook: last week everyone wrote a correct algorithm for finding a room, but if two correct pseudocode versions differ, there is no rule yet for saying whose is better or proving it. That gap is today's hook.

SLOT 2: Where we are

notes: Point at Week 3. Say: "Weeks 1 and 2 gave us the vocabulary. Today we finally get to measure with it."

REWRITTEN: was a discussion warm-up; now teacher-delivered narration that resolves directly instead of asking the class

SLOT 3: Recap + open wound

NEW: Key Words Today, session 1

notes: Read each term aloud once. Say these four words are today's entire vocabulary, made precise by the end of the lecture.

SLOT 4: The pain (Act 1 / MOTIVATE), zero jargon

notes: Do not say "Big-O" yet. Let the class feel that "correct" alone leaves a real, unanswered question.

notes: Pause on the third row. Say: "We will actually measure this row, precisely, later today."

SLOT 5: Cost of not knowing, split: the costs alone here, the industry note next

NEW: continuation of Cost of Not Knowing

SLOT 6: Driving question

SLOT 7: Learning outcomes

NEW: Assignment 1 announcement

notes: Say: "You have two full weeks. Start the pseudocode part now - the proof techniques you need for Part 2 are today's entire lecture."

SLOT 8: Origin

SLOT 9: Core concept

NEW: Key Words Today, session 2

notes: Read each term aloud. Say: "You will use every one of these words in Assignment 1, due Week 5."

MERGED: the four reading-the-definition steps onto one slide

NEW: dense worked example, Big-O proof, simple tier. Reuses the deck's own former Check-Yourself numbers, since they already are the "smallest instructive case."

NEW: dense worked example, Big-O proof, moderate tier. Reuses the deck's exact existing 3n^2+10n+7 proof and numeric check table.

NEW: dense worked example, Big-O/Theta proof, harder tier. Reuses the deck's exact existing n(n-1)/2 = Theta(n^2) two-sided proof.

NEW: math toolbox (1 of 2), before the growth-rate hierarchy

NEW: math toolbox (2 of 2)

MERGED: hierarchy badges + tractable/intractable grouping

NEW: dense worked example, placing growth rates on the hierarchy. Folds the old Check-Yourself pair and the sqrt(n)/n^1.5 placement slide, reusing exact existing content.

MERGED: real-numbers table + the "what uncomputable means" callout

SPLIT for overflow: "what uncomputable means" now gets its own slide

MERGED: space complexity definitions + "same machinery" note + folded check-yourself content

SLOT N-2: Worked example. Merged into one dense slide, reusing the deck's exact existing timing numbers.

SLOT N-1: Common mistakes, merged into one slide

NEW: Key Words Today, session 3

notes: Read each term aloud. Say: "Today formalized cost for algorithms with a known, fixed shape. Next week, algorithms whose shape calls itself."

SLOT N+1: Limits (Act 4 / CLOSE), becomes Week 4 slot 4

SLOT N+2: Bridge

NEW: "Where This Week Lives in CLRS" reference slide, immediately before Summary

SLOT N+3: Summary

SPLIT for overflow

SLOT N+4: Thank You