KatInterview

Head Counts in n Fair Coin Tosses: Sequences and Tail Odds

Math & Bit ManipulationAuto-graded · 22 test cases
EasyAuto-gradedMath & Bit Manipulationcombinatoricsbinomialprobability

Last updated

Compute the number of sequences, the chance of exactly 3 heads, and the chance of at most 3 heads for n fair coin tosses, using binomial counting and handling small n.

Fair Coin Tosses: Counting and Probabilities

A fair coin is tossed n times. Each toss is independent, and heads and tails are equally likely. Write a function that returns three values describing the experiment.

Task

Given a non-negative integer n, return a dictionary with exactly these keys:

  • "total_sequences": the number of distinct ordered sequences of heads and tails of length n. This is an integer.
  • "exactly_3_heads": the probability that exactly 3 of the n tosses are heads.
  • "at_most_3_heads": the probability that the number of heads is 0, 1, 2, or 3.

Rules and edge cases

  • Every sequence of length n is equally likely, so a probability is the number of favourable sequences divided by total_sequences.
  • If n < 3, exactly 3 heads is impossible, so "exactly_3_heads" is 0.
  • If n <= 3, every outcome has at most 3 heads, so "at_most_3_heads" is 1.
  • For n = 0 there is exactly one sequence, the empty one.
  • Compute each probability as an exact integer count divided once by total_sequences. Do not multiply many small floats together, so your values match the expected ones exactly.

Constraints

  • 0 <= n <= 1000
  • n is an integer.
  • The returned dictionary must contain exactly the three keys above.

Examples

Example 1

Input: fair_coin_head_stats(10)

Output: {'total_sequences': 1024, 'exactly_3_heads': 0.1171875, 'at_most_3_heads': 0.171875}

Example 2

Input: fair_coin_head_stats(3)

Output: {'total_sequences': 8, 'exactly_3_heads': 0.125, 'at_most_3_heads': 1}

Example 3

Input: fair_coin_head_stats(0)

Output: {'total_sequences': 1, 'exactly_3_heads': 0, 'at_most_3_heads': 1}

Example 4

Input: fair_coin_head_stats(12)

Output: {'total_sequences': 4096, 'exactly_3_heads': 0.0537109375, 'at_most_3_heads': 0.072998046875}

Hints

Hint 1

Each toss has 2 outcomes, so the total number of ordered sequences is a power of 2.

Hint 2

The number of sequences with exactly k heads is the number of ways to choose which k positions are heads, a binomial coefficient.

Hint 3

For 'at most 3', add the counts for k = 0, 1, 2, 3, but never go beyond n. Divide the integer count by 2**n only once at the end.