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

  • table is a 3 x 3 list of non-negative integers following the row order ["18-30", "31-50", "51+"] and column order ["Running", "Biking", "Swimming"].
  • At least one respondent in table prefers "Biking" (if the "Biking" column sums to 0, raise ValueError).
  • Return an irreducible fraction string "p/q" with q >= 1 and gcd(p, q) == 1 (boundary probabilities 0 and 1 must still include the slash as "0/1" and "1/1").

Step-by-step walkthrough

  1. Understand the table layout and output format

    The input table is a 3 x 3 matrix (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       180
    

    We want the conditional probability P(Age 31-50 | Biking) formatted as a reduced fraction string "p/q" (such as "13/32"), where p and q share no common divisor above 1. Boundary values 0 and 1 keep the "p/q" slash format ("0/1" and "1/1").

  2. 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 column 1 (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 bikers
    

    Applying 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 total 800 cancels completely!

  3. Sum the Biking column and read the 31-50 biker count

    Named index constants AGE_31_50_ROW = 1 and BIKING_COL = 1 make row/column lookups unmistakable: 1. Sum row[BIKING_COL] across all rows of table to compute total_bikers (the denominator). If total_bikers == 0, conditioning on Biking is undefined, so raise ValueError. 2. Read table[AGE_31_50_ROW][BIKING_COL] to extract bikers_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]
    
  4. 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 / 3 rounds to 0.3333333333333333). Instead, keep both counts as Python integers and divide each by math.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 of str(Fraction(numerator, denominator)): Fraction formats whole integers "0" and "1" without /1, whereas format_reduced_fraction(0, 8) produces "0/1" (gcd(0, 8) = 8) and format_reduced_fraction(12, 12) produces "1/1" (gcd(12, 12) = 12).

  5. 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 13 is prime and does not divide 32, "13/32" is completely irreducible.

  6. 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), where r is the number of age rows (3 here) and M is total_bikers. Summing column 1 visits r cells (O(1) for a 3 x 3 matrix), and math.gcd runs the Euclidean algorithm (repeatedly replacing the larger integer with its remainder modulo the smaller one) in O(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): Because math.gcd(0, d) equals d, 0 // d is 0 and d // d is 1, returning "0/1".
  • Every cyclist is aged 31–50 (bikers_aged_31_50 == total_bikers): math.gcd(d, d) equals d, 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), so ValueError is raised.
  • Very large respondent counts: Arbitrary-precision Python integers avoid float rounding completely, reducing 333,333 / 1,333,332 cleanly to "1/4".
  • Running and Swimming counts: Because we condition strictly on Biking, columns 0 and 2 do not influence the output.

Common mistakes

  • Dividing by the grand total (78 / 800 = "39/400"): Computes the unconditional joint probability P(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, computing P(Biking | 31-50) instead of P(31-50 | Biking).
  • Returning an unreduced string ("78/192"): Leaves common factor 6 uncancelled, violating the irreducible fraction requirement.
  • Wrapping a float inside Fraction(num / den): Passing 1 / 3 instead of (1, 3) converts a rounded 53-bit binary float into "6004799503160661/18014398509481984".
  • Returning str(Fraction(numerator, denominator)) directly: Formats 0/8 as "0" and 12/12 as "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 row 1 (31-50) the restricted universe instead of column 1 (Biking). The numerator remains the exact same intersection cell (78 in Example 1), while the denominator becomes the row 1 sum 130 + 78 + 92 = 300, simplifying via gcd(78, 300) = 6 to "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 all 9 cells (800 in Example 1) while the numerator stays table[1][1] (78). Reducing by gcd(78, 800) = 2 gives "39/400", matching the product rule P(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 s swimmers (of whom t are aged 31-50) into Biking shifts Example 1's probability from 78 / 192 = 13 / 32 ≈ 40.6% to (78 + t) / (192 + s). That ratio rises when the reclassified swimmers have a higher 31-50 share than existing cyclists (t / s > 13 / 32) and falls when their 31-50 share is lower (t / s < 13 / 32); in Example 1, swimmers overall are only 92 / 308 ≈ 29.9% aged 31-50, so folding in all swimmers (or a representative random sample) lowers the conditional probability to 170 / 500 = "17/50" (34.0%).

Follow-up questions

Similar questions

More SIG (Susquehanna) interview questions

All 44 SIG (Susquehanna) questions →