Heads in Fair Coin Flips
Updated
Problem statement
You flip a fair coin n times. Each flip is heads or tails with equal chance, independently of the others.
If atLeast is false, return the probability of getting exactly k heads. If atLeast is true, return the probability of getting k or more heads.
Answers within 10-9 of the correct value are accepted.
Function
headsProbability(n: int, k: int, atLeast: boolean) → doubleExamples
Example 1
n = 3k = 2atLeast = truereturn = 0.5The 8 sequences of three flips are equally likely. HHT, HTH and THH have two heads and HHH has three, so 4 of the 8 count, and the answer is 4/8 = 0.5.
Example 2
n = 3k = 2atLeast = falsereturn = 0.375Only HHT, HTH and THH have exactly two heads, so the answer is 3/8 = 0.375.
Example 3
n = 2k = 1atLeast = truereturn = 0.75Of HH, HT, TH and TT, only TT has no heads, so the answer is 1 - 1/4 = 0.75.
Example 4
n = 10k = 5atLeast = falsereturn = 0.24609375There are 2^10 = 1024 equally likely sequences, and C(10, 5) = 252 of them have exactly five heads. The answer is 252/1024 = 0.24609375.
Example 5
n = 4k = 0atLeast = truereturn = 1.0Every sequence has at least zero heads, so the answer is 1.0.
Constraints
1 <= n <= 10000 <= k <= n
More Jane Street Phone Screen questions
- Maximum-Scoring Consecutive Tree LevelsPHONE SCREEN · Seen Nov 2026
- Tree Selection and VisibilityPHONE SCREEN · Seen Nov 2026
- Load/Store Arithmetic InterpreterPHONE SCREEN · Seen Oct 2026
- Instrument Stack Language JumpsPHONE SCREEN · Seen Oct 2026
- Run a Stack Language InterpreterPHONE SCREEN · Seen Oct 2026
- Positive-Integer Expression EvaluationPHONE SCREEN · Seen Oct 2026
- Add Two Integers Given as StringsPHONE SCREEN · Seen Sep 2026
- Angle Between Clock HandsPHONE SCREEN · Seen Jul 2026
- Route Length From Two CyclistsPHONE SCREEN · Seen Jul 2026
- Sort TradesPHONE SCREEN · ONSITE INTERVIEW · Seen Jul 2026
Similar questions at other companies
- Biased Coin: Probability of Exactly h HeadsAkuna Capital · PHONE SCREENAkuna Capital interview questions
- Probability of Consecutive HeadsSquarepoint Capital · PHONE SCREENSquarepoint Capital interview questions
- Count Routes Through a City GridIMC Trading · PHONE SCREENIMC Trading interview questions
- Strictly More Heads with Fewer CoinsSusquehanna International Group (SIG) · PHONE SCREENSusquehanna International Group (SIG) interview questions
- Count Clean Attendance LogsRippling · PHONE SCREENRippling interview questions
- Count Array DerangementsInMobi · PHONE SCREENInMobi interview questions
- Count Staircases with Strictly Increasing StepseBay · ONSITE INTERVIEWeBay interview questions
- Count Nondecreasing Digit-Sum ArraysMicrosoft · OAMicrosoft interview questions
- Stable Workload Redistribution TreesTower Research Capital · OA
- Count Valid A-B-C Sequences Under a Modulo-Four RuleInfosys · OAInfosys interview questions