Conditional Age-Bracket Probability Given Cycling
Easy · Statistics & Math · Data Scientist · Online Assessment
Problem Statement
A community wellness study cross-tabulates respondents along two dimensions: age bracket (rows) and primary workout activity (columns). You are given a 3 x 3 integer matrix table (List[List[int]]) with fixed row and column meanings:
- Rows (
0, 1, 2):"18-30","31-50", and"51+" - Columns (
0, 1, 2):"Running","Biking", and"Swimming"
Suppose one respondent is chosen uniformly at random from the survey and is known to list "Biking" as their primary workout activity. Implement probability_31_50_given_biking(table) to compute the conditional probability that this respondent belongs to the "31-50" age bracket, formatted as an irreducible fraction string "p/q".
Examples
Example 1
| Age Bracket | Running (col 0) | Biking (col 1) | Swimming (col 2) |
|---|---|---|---|
| 18-30 (row 0) | 90 | 54 | 36 |
| 31-50 (row 1) | 130 | 78 | 92 |
| 51+ (row 2) | 80 | 60 | 180 |
Input: table = [[90, 54, 36], [130, 78, 92], [80, 60, 180]]
Output: "13/32"
Explanation: Restricting attention to the "Biking" column gives 54 + 78 + 60 = 192 cyclists in total, of whom 78 sit in the "31-50" row. Dividing numerator and denominator by gcd(78, 192) = 6 simplifies 78/192 to "13/32".
Example 2
Input: table = [[40, 15, 25], [60, 45, 35], [50, 30, 100]]
Output: "1/2"
Explanation: Across all three age brackets there are 15 + 45 + 30 = 90 cyclists, and 45 of them are aged "31-50". Simplifying 45/90 yields "1/2".
Constraints
tableis a3 x 3list of non-negative integers following the row order["18-30", "31-50", "51+"]and column order["Running", "Biking", "Swimming"].- At least one respondent in
tableprefers"Biking"(if the"Biking"column sums to0, raiseValueError). - Return an irreducible fraction string
"p/q"withq >= 1andgcd(p, q) == 1(boundary probabilities0and1must still include the slash as"0/1"and"1/1").
Step-by-step walkthrough
Understand the table layout and output format
The input
tableis a3 x 3matrix (List[List[int]]) cross-tabulating respondent counts by age bracket (rows) and primary workout activity (columns):col 0 col 1 col 2 Running Biking Swimming row 0 (18-30) 90 54 36 row 1 (31-50) 130 78 92 row 2 (51+) 80 60 180We want the conditional probability
P(Age 31-50 | Biking)formatted as a reduced fraction string"p/q"(such as"13/32"), wherepandqshare no common divisor above1. Boundary values0and1keep the"p/q"slash format ("0/1"and"1/1").Key idea: "given Biking" zooms in on one column
In conditional probability, whatever follows "given" restricts the sample space. Learning that the selected respondent prefers
"Biking"rules out every runner and swimmer — only respondents inside column1(Biking) remain possible:Running [ Biking ] Swimming row 0 (18-30) ... [ 54 ] ... row 1 (31-50) ... [ (78) ] ... <-- numerator: bikers aged 31-50 row 2 (51+) ... [ 60 ] ... ---------- 192 <-- denominator: all bikersApplying the formal definition
P(A | B) = P(A and B) / P(B)yields the exact same fraction: -P(31-50 and Biking) = 78 / 800-P(Biking) = 192 / 800-(78 / 800) / (192 / 800) = 78 / 192— the survey total800cancels completely!Sum the Biking column and read the 31-50 biker count
Named index constants
AGE_31_50_ROW = 1andBIKING_COL = 1make row/column lookups unmistakable: 1. Sumrow[BIKING_COL]across all rows oftableto computetotal_bikers(the denominator). Iftotal_bikers == 0, conditioning on Biking is undefined, so raiseValueError. 2. Readtable[AGE_31_50_ROW][BIKING_COL]to extractbikers_aged_31_50(the numerator).AGE_31_50_ROW = 1 BIKING_COL = 1 total_bikers = 0 for row in table: total_bikers += row[BIKING_COL] if total_bikers == 0: raise ValueError("cannot condition on Biking when zero respondents bike") bikers_aged_31_50 = table[AGE_31_50_ROW][BIKING_COL]Simplify the fraction in exact integer arithmetic
Avoid floating-point division
/when an exact reduced fraction is required — binary floats lose exactness on non-powers-of-two denominators (for instance,1 / 3rounds to0.3333333333333333). Instead, keep both counts as Python integers and divide each bymath.gcd(numerator, denominator)using integer floor division//:def format_reduced_fraction(numerator: int, denominator: int) -> str: # Divide both integers by their greatest common divisor so the fraction is irreducible. # Because gcd(0, d) == d and gcd(d, d) == d, 0 formats as "0/1" and 1 formats as "1/1". common_divisor = gcd(numerator, denominator) reduced_num = numerator // common_divisor reduced_den = denominator // common_divisor return f"{reduced_num}/{reduced_den}"Formatting
"p/q"explicitly also avoids a subtle quirk ofstr(Fraction(numerator, denominator)):Fractionformats whole integers"0"and"1"without/1, whereasformat_reduced_fraction(0, 8)produces"0/1"(gcd(0, 8) = 8) andformat_reduced_fraction(12, 12)produces"1/1"(gcd(12, 12) = 12).Trace Example 1 step by step
Let's trace
[[90, 54, 36], [130, 78, 92], [80, 60, 180]]:1. Sum column 1 (Biking): total_bikers = 54 + 78 + 60 = 192 2. Read row 1, col 1: bikers_aged_31_50 = 78 3. Greatest common divisor: gcd(78, 192) = 6 4. Reduce numerator & denom: 78 // 6 = 13, 192 // 6 = 32 5. Format string: "13/32"Because
13is prime and does not divide32,"13/32"is completely irreducible.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from math import gcd # Table layout: rows are [0: "18-30", 1: "31-50", 2: "51+"]; columns are [0: "Running", 1: "Biking", 2: "Swimming"]. AGE_31_50_ROW = 1 BIKING_COL = 1 def format_reduced_fraction(numerator: int, denominator: int) -> str: # Divide both integers by their greatest common divisor so the fraction is irreducible. # Because gcd(0, d) == d and gcd(d, d) == d, 0 formats as "0/1" and 1 formats as "1/1". common_divisor = gcd(numerator, denominator) reduced_num = numerator // common_divisor reduced_den = denominator // common_divisor return f"{reduced_num}/{reduced_den}" def probability_31_50_given_biking(table: List[List[int]]) -> str: # Conditioning on "Biking" restricts the sample space strictly to the Biking column. total_bikers = 0 for row in table: total_bikers += row[BIKING_COL] if total_bikers == 0: raise ValueError("cannot condition on Biking when zero respondents bike") # Among bikers, count how many also fall into the "31-50" age row. bikers_aged_31_50 = table[AGE_31_50_ROW][BIKING_COL] return format_reduced_fraction(bikers_aged_31_50, total_bikers)✅ Submit now — all tests should pass.
Intuition & how it works
Picture all 800 respondents from Example 1 gathered in an auditorium, and an organizer announces: "Anyone whose primary workout is Running or Swimming, please exit!" Only the cyclists stay seated. Evaluating a conditional probability (the probability of event A occurring given event B has already occurred, written P(A | B)) on a contingency table (a two-way frequency matrix cross-classifying two categorical variables like age bracket and workout activity) does the exact same filtering: "given Biking" restricts the universe exclusively to the "Biking" column's marginal total (the sum of counts down one column or across one row), and we measure what fraction of those cyclists sit in the "31-50" row.
Why do common approaches stumble here? First, dividing 78 by the grand total 800 calculates the joint probability (the chance a random respondent from the whole study both bikes and is aged 31–50), whereas dividing 78 by the "31-50" row sum 300 calculates the reversed conditional P(Biking | 31-50) — the group named after "given" must always be the denominator! Second, using floating-point / loses exactness on repeating binary fractions, whereas dividing both integers by their greatest common divisor (GCD) (the largest positive integer dividing both counts evenly) yields an exact irreducible fraction (a "p/q" ratio whose numerator and denominator share no common factor greater than 1).
Here is the step-by-step trace on Example 1 ([[90, 54, 36], [130, 78, 92], [80, 60, 180]]):
Biking column (index 1): 54 (age 18-30), 78 (age 31-50), 60 (age 51+)
1. Restrict universe to Biking column: total_bikers = 54 + 78 + 60 = 192
2. Count 31-50 inside that column: bikers_aged_31_50 = 78
3. Reduce 78 / 192 via GCD: gcd(78, 192) = 6 -> (78 // 6) / (192 // 6) = "13/32"
Complexity
- Time:
O(r + log M), whereris the number of age rows (3here) andMistotal_bikers. Summing column1visitsrcells (O(1)for a3 x 3matrix), andmath.gcdruns the Euclidean algorithm (repeatedly replacing the larger integer with its remainder modulo the smaller one) inO(log M)integer divisions. - Space:
O(1), using only a handful of scalar integers (total_bikers,bikers_aged_31_50,common_divisor) and the output string.
Edge cases
- Zero cyclists aged 31–50 (
bikers_aged_31_50 == 0,total_bikers > 0): Becausemath.gcd(0, d)equalsd,0 // dis0andd // dis1, returning"0/1". - Every cyclist is aged 31–50 (
bikers_aged_31_50 == total_bikers):math.gcd(d, d)equalsd, returning"1/1"rather than"1"so the"p/q"contract always holds. - Zero cyclists across all rows (
total_bikers == 0): Conditioning on a zero-probability event is undefined (0 / 0), soValueErroris raised. - Very large respondent counts: Arbitrary-precision Python integers avoid float rounding completely, reducing
333,333 / 1,333,332cleanly to"1/4". - Running and Swimming counts: Because we condition strictly on
Biking, columns0and2do not influence the output.
Common mistakes
- Dividing by the grand total (
78 / 800 = "39/400"): Computes the unconditional joint probabilityP(31-50 and Biking)across all respondents rather than conditioning on cyclists. - Dividing by the
"31-50"row sum (78 / 300 = "13/50"): Inverts the event and the condition, computingP(Biking | 31-50)instead ofP(31-50 | Biking). - Returning an unreduced string (
"78/192"): Leaves common factor6uncancelled, violating the irreducible fraction requirement. - Wrapping a float inside
Fraction(num / den): Passing1 / 3instead of(1, 3)converts a rounded 53-bit binary float into"6004799503160661/18014398509481984". - Returning
str(Fraction(numerator, denominator))directly: Formats0/8as"0"and12/12as"1", omitting"/1"on boundary probabilities.
Follow-up questions
- How does the computation change if the conditioning is reversed—finding the probability that a respondent prefers Biking given they belong to the 31-50 age bracket? Conditioning on
"31-50"makes row1(31-50) the restricted universe instead of column1(Biking). The numerator remains the exact same intersection cell (78in Example 1), while the denominator becomes the row1sum130 + 78 + 92 = 300, simplifying viagcd(78, 300) = 6to"13/50". - How would you compute the unconditional joint probability that one person drawn at random from everyone surveyed both prefers Biking and is aged 31-50? Without a
"given"clause, the denominator is the grand total across all9cells (800in Example 1) while the numerator staystable[1][1](78). Reducing bygcd(78, 800) = 2gives"39/400", matching the product ruleP(31-50 | Biking) * P(Biking) = (78 / 192) * (192 / 800). - Suppose a subset of Swimming respondents is reclassified into the Biking column; under what condition does P(31-50 | Biking) rise versus fall? Moving
sswimmers (of whomtare aged31-50) into Biking shifts Example 1's probability from78 / 192 = 13 / 32 ≈ 40.6%to(78 + t) / (192 + s). That ratio rises when the reclassified swimmers have a higher31-50share than existing cyclists (t / s > 13 / 32) and falls when their31-50share is lower (t / s < 13 / 32); in Example 1, swimmers overall are only92 / 308 ≈ 29.9%aged31-50, so folding in all swimmers (or a representative random sample) lowers the conditional probability to170 / 500 = "17/50"(34.0%).
Follow-up questions
- How does the computation change if the conditioning is reversed—finding the probability that a respondent prefers Biking given they belong to the 31-50 age bracket?
- How would you compute the unconditional joint probability that one person drawn at random from everyone surveyed both prefers Biking and is aged 31-50?
- Suppose a subset of Swimming respondents is reclassified into the Biking column; under what condition does P(31-50 | Biking) rise versus fall?
Similar questions
- Knights and Knaves Two-Claim Deductions
- Posterior Probability of Plant A Given k Red Draws
- Expected Payout of a Two-Dice Roll Game
- Expected Die Rolls for Stopping Patterns
- Goal-Reaching Probability Under Bold Wagering
- Muffin Inventory Sufficiency Probability
More SIG (Susquehanna) interview questions
- Posterior Probability of Plant A Given k Red Draws Medium
- Expected Payout of a Two-Dice Roll Game Easy
- Probability of Concurrent Bloom Windows Easy Pro
- Posterior Probability Given a Losing Rabbit Easy Pro
- Cookie Assortment Combination Counts Easy Pro
- Streaming Equal-Step Triple Counts Under Updates Medium Pro
- Grid Paths Without Triple Consecutive Steps Easy Pro
- Cat Ownership Puzzle Under Comparative Honesty Rules Easy Pro
- FIFO Inventory Register with Atomic Checkouts Easy Pro
- Count Ants from Total Leg Observations Easy Pro