Week 4: Nested Iterations & Birthday Paradox

3355 words
17 min read
2026-09-12T00:00:00.000Z
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

Nested loops, pairwise element comparisons, quadratic complexity intuition, birthday paradox, and data binning. # Computational Thinking — Week 4: Nested Iterations & Birthday Paradox IITM’s CT Week 4 covers **nested iterations, the Birthday Paradox, and binning**.

Computational Thinking — Week 4: Nested Iterations & Birthday Paradox

IITM’s CT Week 4 covers nested iterations, the Birthday Paradox, and binning.

TL;DR

Week 3 had multiple loops one after another.
Week 4 introduces:
text
loop
    inside another loop
That changes the computational pattern from roughly:
n+nn+n
to something often closer to:
n2.n^2.
The three core ideas are:
  • nested iteration → compare/process combinations of items
  • birthday paradox → collisions become likely much sooner than intuition suggests
  • binning → group continuous or wide-range values into intervals/categories

1. Nested iteration

A nested loop means one loop executes inside another.
Example:
text
for each x:
    for each y:
        process(x, y)
The inner loop runs fully for every iteration of the outer loop.

2. Simple example

Suppose:
text
X = [1, 2]
Y = [A, B, C]
Algorithm:
text
for each x in X:
    for each y in Y:
        output (x, y)
Outputs:
text
(1, A)
(1, B)
(1, C)
(2, A)
(2, B)
(2, C)
Total:
2×3=6.2\times3=6.

3. Outer vs inner loop

In:
text
for each x:
    for each y:
        ...
x changes slowly.
For each fixed x, y runs through all its values.
Example:
text
x = 1
    y = A
    y = B
    y = C

x = 2
    y = A
    y = B
    y = C
That execution order matters in tracing.

4. Number of executions

If outer loop executes:
mm
times and inner loop executes:
nn
times for each outer iteration, body executes:
mn\boxed{mn}
times.
If both use nn items:
n2\boxed{n^2}
body executions.

5. Nested vs sequential loops

Sequential

text
for each x in data:
    ...

for each y in data:
    ...
Rough work:
n+n=2n.n+n=2n.

Nested

text
for each x in data:
    for each y in data:
        ...
Rough work:
n2.n^2.
This is a major conceptual difference.

6. Pairwise comparison

Nested loops are natural when comparing items with other items.
Example:
compare every student with every other student.
Conceptually:
text
for each student A:
    for each student B:
        compare A and B
This examines ordered pairs.

7. Ordered pairs

If there are:
nn
items, nested loops over the same collection may generate:
n2n^2
ordered pairs:
(i,j).(i,j).
These include:
  • self-pairs: (i,i)(i,i)
  • both directions: (i,j)(i,j) and (j,i)(j,i)

8. Example

For:
text
A, B, C
full ordered-pair loop gives:
text
(A,A)
(A,B)
(A,C)
(B,A)
(B,B)
(B,C)
(C,A)
(C,B)
(C,C)
Total:
32=9.3^2=9.

9. Avoiding self-comparisons

If comparing distinct items, use a condition:
text
if A != B:
    compare
Then self-pairs are removed.
Number of ordered distinct pairs:
n(n−1)\boxed{n(n-1)}

10. Avoiding duplicate reverse pairs

Sometimes:
(A,B)(A,B)
and:
(B,A)(B,A)
represent the same comparison.
Then each unordered pair should appear once.
Number of such pairs:
(n2)=n(n−1)2\boxed{ \binom n2 = \frac{n(n-1)}2 }
This links CT directly to Stats combinatorics.

11. Typical unique-pair pseudocode

Conceptually:
text
for i from 1 to n:
    for j from i+1 to n:
        compare item[i], item[j]
This produces each unordered pair exactly once.

12. Example

For:
text
A, B, C, D
unique pairs:
text
AB
AC
AD
BC
BD
CD
Total:
(42)=6.\binom42=6.

13. Nested-loop trace

Consider:
text
count = 0

for each x in [1, 2]:
    for each y in [10, 20, 30]:
        count = count + 1
Inner body runs:
2×3=62\times3=6
times.
So:
count=6\boxed{count=6}

14. Nested-loop accumulation

Example:
text
total = 0

for each x in [1, 2]:
    for each y in [3, 4]:
        total = total + x*y
Terms:
1⋅3+1⋅4+2⋅3+2⋅4.1\cdot3 + 1\cdot4 + 2\cdot3 + 2\cdot4.
So:
3+4+6+8=21.3+4+6+8 = \boxed{21}.

15. Inner variable resets conceptually

For each new outer value, inner iteration begins again from its start.
Example:
text
x = 1 → y = 1,2,3
x = 2 → y = 1,2,3
Do not continue y from its previous ending state unless pseudocode explicitly says so.

16. Filtering inside nested loops

Suppose we only want pairs whose sum exceeds 10:
text
for each x:
    for each y:
        if x + y > 10:
            count = count + 1
This combines:
  • nested iteration
  • filtering
  • counting

17. Nested loops over records

Example:
Find whether any two students have the same score.
text
for each student A:
    for each student B after A:
        if score(A) == score(B):
            ...
This is exactly the kind of pattern that connects to the Birthday Paradox.

18. Collision

A collision occurs when two distinct items map to the same value/category.
Examples:
  • two people share a birthday
  • two keys hash to same bucket
  • two students have same score
  • two files have same identifier
The Birthday Paradox is fundamentally a collision problem.

19. Birthday Paradox

Suppose birthdays are uniformly distributed across:
365365
days and ignore leap years.
Question:
How many people are needed before the probability that at least two share a birthday becomes surprisingly large?
Intuition often guesses something near:
183.183.
But the famous result is that with only:
23\boxed{23}
people, collision probability exceeds roughly:
50%.50\%.
The course topic is about understanding why collisions become likely quickly.

20. Why intuition fails

People often think:
one person's birthday must match mine.
That probability grows slowly.
But the real event is:
any pair shares a birthday.
With nn people, number of pairs is:
(n2)=n(n−1)2\boxed{ \binom n2 = \frac{n(n-1)}2 }
That grows quadratically.

21. Pair count for 23 people

Number of pairs:
(232)=23⋅222=253.\binom{23}{2} = \frac{23\cdot22}{2} = \boxed{253}.
So even though 23 is much smaller than 365, there are already 253 pairwise opportunities for a collision.
That is the core intuition.

22. Direct calculation is awkward

The event:
at least one shared birthday
can happen in many overlapping ways.
Directly adding collision cases causes overcounting.
So use the complement:
P(collision)=1−P(all birthdays distinct)\boxed{ P(\text{collision}) = 1-P(\text{all birthdays distinct}) }

23. Probability all birthdays are distinct

For nn people:
First person:
365365\frac{365}{365}
Second must avoid first birthday:
364365\frac{364}{365}
Third must avoid previous two:
363365\frac{363}{365}
and so on.
Thus:
P(all distinct)=365365⋅364365⋅363365⋯365−n+1365\boxed{ P(\text{all distinct}) = \frac{365}{365} \cdot \frac{364}{365} \cdot \frac{363}{365} \cdots \frac{365-n+1}{365} }

24. Compact formula

For:
n≤365,n\leq365, P(all distinct)=365⋅364⋯(365−n+1)365n.P(\text{all distinct}) = \frac{ 365\cdot364\cdots(365-n+1) }{ 365^n }.
Equivalent factorial form:
P(all distinct)=365!(365−n)!365n\boxed{ P(\text{all distinct}) = \frac{365!} {(365-n)!365^n} }

25. Collision probability

Therefore:
P(at least one shared birthday)=1−365!(365−n)!365n\boxed{ P(\text{at least one shared birthday}) = 1- \frac{365!} {(365-n)!365^n} }
for:
n≤365.n\leq365.

26. Why complement is natural

This mirrors Stats probability:
P(at least one)=1−P(none).P(\text{at least one}) = 1-P(\text{none}).
"No collision" is structurally simple:
text
person 1: any day
person 2: avoid 1 used day
person 3: avoid 2 used days
...
So complement makes the problem manageable.

27. Nested-loop interpretation

A simple collision detector might conceptually do:
text
collision = False

for each person i:
    for each person j after i:
        if birthday[i] == birthday[j]:
            collision = True
This examines pairs.
So the Birthday Paradox links:
  • nested iteration
  • pair counting
  • probability

28. Pairwise work grows quickly

For:
n=10,n=10,
pairs:
45.45.
For:
n=100,n=100,
pairs:
4950.4950.
For:
n=1000,n=1000,
pairs:
499500.499500.
Quadratic growth becomes expensive quickly.

29. Computational lesson

Birthday-style collision problems reveal why:
O(n2)O(n^2)
pairwise algorithms can become costly.
Even if the course does not formally emphasize asymptotic notation yet, the practical idea is:
nested loops can create many more operations than sequential loops.

30. Binning

Binning means grouping values into intervals or categories called bins.
Example ages:
text
12, 17, 21, 25, 34, 41
Possible bins:
text
0–19
20–39
40–59
Then counts:
text
0–19  → 2
20–39 → 3
40–59 → 1

31. Why bin data?

Binning helps:
  • summarize large datasets
  • reduce detail
  • reveal distribution shape
  • construct histograms
  • categorize continuous/numerical data
It converts many exact values into fewer groups.

32. Example

Marks:
text
21, 35, 42, 48, 53, 68, 71, 82, 90
Bins:
text
0–20
21–40
41–60
61–80
81–100
Counts:
BinCount
0–200
21–402
41–603
61–802
81–1002

33. Bin membership

A bin needs a precise rule.
Example:
0≤x<100\leq x<10 10≤x<2010\leq x<20 20≤x<30.20\leq x<30.
Using half-open intervals avoids ambiguity at boundaries.

34. Boundary problem

Suppose bins are written vaguely as:
text
0–10
10–20
Where does:
1010
belong?
Ambiguous.
Better:
[0,10)[0,10)
and:
[10,20).[10,20).
Then 10 clearly belongs to second bin.

35. Binning pseudocode

Example:
text
low = 0
medium = 0
high = 0

for each x:
    if x < 10:
        low = low + 1
    else if x < 20:
        medium = medium + 1
    else:
        high = high + 1
This classifies each item into one bin.

36. Why else if is useful

Suppose:
x=5.x=5.
It satisfies:
text
x < 10
and also:
text
x < 20
If you used two independent ifs, it could be counted twice.
Using:
text
if
else if
else
ensures exactly one category is selected.

37. Bins should be mutually exclusive

Ideally, one observation belongs to exactly one bin.
So bins should not overlap.
Bad:
[0,10][0,10]
and:
[10,20][10,20]
because:
1010
belongs to both.

38. Bins should be exhaustive

If every possible valid value must be classified, the bins should collectively cover the entire desired range.
Example:
(−∞,0)(-\infty,0) [0,10)[0,10) [10,∞)[10,\infty)
covers every real value.

39. Equal-width bins

Example:
0−10, 10−20, 20−300-10,\ 10-20,\ 20-30
all have width:
10.10.
Equal-width bins make comparisons straightforward.

40. Unequal-width bins

Sometimes bins may have different widths.
Example:
0−100-10 10−5010-50 50−100.50-100.
Raw counts may then be misleading when comparing histogram heights, because wider bins naturally capture more possible values.
That becomes more important in formal statistics.

41. Binning loses information

Original values:
text
21, 22, 39
may all fall into:
text
20–39
After binning, their exact values are lost.
So binning trades:
detail→simplicity\boxed{ \text{detail} \rightarrow \text{simplicity} }

42. Too few bins

If bins are too wide:
  • important structure disappears
  • peaks may merge
  • distribution looks oversimplified
Example:
text
0–100
as one bin tells almost nothing.

43. Too many bins

If bins are too narrow:
  • representation becomes noisy
  • almost every value may get its own bin
  • summarization benefit disappears
So bin choice is a tradeoff.

44. Binning and histograms

A histogram essentially displays:
how many observations fall into each numerical bin.
So CT binning connects directly to descriptive statistics.

45. Binning algorithm with computed index

Sometimes equal-width bins can be indexed mathematically.
Suppose bin width:
w=10w=10
and values are nonnegative.
One conceptual bin index is:
⌊x10⌋.\left\lfloor\frac{x}{10}\right\rfloor.
Examples:
x=7⇒0x=7 \Rightarrow0 x=23⇒2x=23 \Rightarrow2 x=48⇒4.x=48 \Rightarrow4.
This is a useful generalization.

46. Frequency array intuition

Suppose bins are numbered:
0,1,2,3.0,1,2,3.
Maintain:
text
count[0]
count[1]
count[2]
count[3]
For each value:
  1. determine bin
  2. increment that bin's count
Conceptually:
text
bin = determineBin(x)
count[bin] = count[bin] + 1

47. Binning is a form of filtering/classification

Each value is tested against conditions and assigned to exactly one category.
So Week 4 binning builds directly on Week 2 selection.

48. Nested loops and binning

A naive binning algorithm could compare each value against every bin:
text
for each x:
    for each bin:
        if x belongs to bin:
            increment bin count
This is another nested-loop structure.
More efficient strategies may exist depending on bin design.

49. Example trace

Data:
text
4, 12, 8, 21, 17
Bins:
  • low: x<10x<10
  • medium: 10≤x<2010\leq x<20
  • high: x≥20x\geq20
Initialize:
text
low = 0
medium = 0
high = 0
Trace:
xxBinLowMediumHigh
4Low100
12Medium110
8Low210
21High211
17Medium221
Final:
(2,2,1)\boxed{ (2,2,1) }

50. Nested-loop example with condition

Consider:
text
C = 0

for each x in [1,2,3]:
    for each y in [1,2,3]:
        if x < y:
            C = C + 1
Qualifying pairs:
(1,2)(1,2) (1,3)(1,3) (2,3).(2,3).
Therefore:
C=3\boxed{C=3}
which equals:
(32).\binom32.

51. Why x<yx<y removes duplicates

For any distinct pair like:
1,3,1,3,
only one ordering satisfies:
x<y.x<y.
The reverse:
3,13,1
fails.
Self-pairs also fail.
Thus each unordered pair is counted once.

52. Another nested-loop trace

text
S = 0

for each x in [1,2]:
    for each y in [1,2]:
        S = S + x + y
Terms:
(1+1)+(1+2)+(2+1)+(2+2).(1+1)+(1+2)+(2+1)+(2+2).
So:
2+3+3+4=12.2+3+3+4 = \boxed{12}.
Common mistake: inner loop executes once total
Wrong.
In nested iteration, the inner loop executes completely for each outer-loop iteration.
If:
  • outer = 5 times
  • inner = 4 times
body executes:
5×4=205\times4=20
times.

Common mistake: count
n+nn+n instead of n2n^2
Two sequential loops:
n+n.n+n.
Two nested loops:
n×n.n\times n.
Do not confuse their structures.

Common mistake: duplicate pair counting
If you compare:
text
for every i:
    for every j:
then:
(i,j)(i,j)
and:
(j,i)(j,i)
both appear.
If one comparison should count only once, restrict the loops or use a condition.

Common mistake: forget self-pairs
Full Cartesian pair iteration includes:
(i,i).(i,i).
If a person should not be compared with themselves, explicitly exclude those cases.

Common mistake: birthday probability as
n365\frac{n}{365}
The event is not:
someone matches one fixed person's birthday.
It is:
any pair collides.
There are:
(n2)\binom n2
potential pairs.
So:
n365\frac{n}{365}
does not represent the actual collision probability.

Common mistake: direct birthday addition
You cannot simply calculate probability of each pair matching and add all pair probabilities because pair events overlap.
Use the complement approach for the exact calculation.

Common mistake: bin overlap
Bad bin rules:
text
x <= 10
x >= 10 AND x <= 20
Value 10 can belong to both.
Define boundaries consistently.

Common mistake: gap between bins
Bad:
x<10x<10
and:
x>10.x>10.
Where does:
x=10x=10
go?
Nowhere.
Bins should cover boundary cases intentionally.

Common mistake: use independent
ifs for exclusive bins
Suppose:
text
if x < 20:
    A++

if x < 40:
    B++
For:
x=10,x=10,
both bins increment.
If bins are intended to be exclusive, use ordered selection:
text
if ...
else if ...
else

Common mistake: assume binned data preserves exact values
After knowing:
17 observations fall in 20–30
you cannot recover their exact individual values.
Binning is lossy.

Common mistake: ignore bin width
A wider interval may naturally contain more observations.
When interpreting binned data, always inspect interval boundaries and widths.

64. Master nested-loop tracing method

For:
text
for each x:
    for each y:
        body
write a table:
Outer xxInner yyConditionState change
first xfirst y......
first xsecond y......
............
second xfirst y......
Do not attempt to keep everything mentally when the loop is nontrivial.

65. Week 4 conceptual map

text
NESTED ITERATION
│
├── all pairs
├── unique pairs
└── pairwise comparisons
      ↓
Birthday collision problem
      ↓
many pair opportunities
      ↓
unexpectedly high collision probability

BINNING
│
├── define intervals
├── classify each value
└── count per bin

66. Weeks 3 → 4 connection

Week 3:
Loop 1→Loop 2\text{Loop 1} \rightarrow \text{Loop 2}
Week 4:
Loop 1{Loop 2\text{Loop 1} \begin{cases} \text{Loop 2} \end{cases}
That structural change creates pairwise behavior and much faster growth in the number of operations.

67. Connection across your courses

This week quietly connects several things you've already covered:

Maths 1

Cartesian products:
A×BA\times B
behave like nested iteration over all pairs.

Stats 1

Pair counting:
(n2)\binom n2
explains birthday comparisons.
Complement probability:
1−P(no collision)1-P(\text{no collision})
solves the Birthday Paradox.
Histograms use numerical bins.
So CT Week 4 ties several earlier topics together.

68. What you should actually master

By the end of CT Week 4, you should be able to:
  1. Identify nested iterations.
  2. Distinguish nested from sequential loops.
  3. Trace outer and inner iterators correctly.
  4. Calculate how many times a nested body executes.
  5. Recognize full ordered-pair iteration.
  6. Exclude self-pairs when needed.
  7. Avoid double-counting symmetric pairs.
  8. Understand why: (n2)\binom n2 appears in pairwise problems.
  9. Explain the Birthday Paradox intuitively.
  10. Use the complement: P(collision)=1−P(all distinct).P(\text{collision}) = 1-P(\text{all distinct}).
  11. Understand why collision opportunities grow roughly quadratically.
  12. Define bins precisely.
  13. Assign observations to bins.
  14. Keep bins mutually exclusive and exhaustive.
  15. Trace a bin-counting algorithm.
  16. Understand that binning trades detail for a simpler summary.
If these are comfortable, Computational Thinking Week 4 is under control.

Quick Recall & Flashcards

Test your active recall before proceeding to practice problems. Format:
Question :: Answer.
  • Week 4 Diagnostic: If an outer loop runs N times and an inner loop runs N times for each outer iteration, what is the total number of inner loop executions? :: Answer: B — Nested iterations multiply execution counts: N * N = N^2.
  • Week 4 Diagnostic: In the Birthday Paradox, approximately how many people are needed in a room for the probability of a shared birthday to exceed 50%? :: Answer: 23 — The classic Birthday Paradox requires only 23 people for a >= 50.7% chance of at least one shared birthday.

Practice & Self-Check

Attempt these diagnostic questions to verify your operational understanding.
1

Question 1

If an outer loop runs N times and an inner loop runs N times for each outer iteration, what is the total number of inner loop executions?
MCQ
3 Unit Assessment
A. 2N
B. N^2
C. N + 1
D. N log N
2

Question 2

In the Birthday Paradox, approximately how many people are needed in a room for the probability of a shared birthday to exceed 50%?
NAT
3 Unit Assessment

Active Recall Session

Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.