Probability of Exactly K Heads
Updated
Problem statement
A fair coin is tossed n times. Each toss comes up heads or tails with probability 1/2 each, independently of the other tosses.
Return the probability of getting exactly k heads, as an exact fraction in lowest terms. Write it as a string "p/q", where p and q are positive integers with no common factor greater than 1.
Function
probabilityOfKHeads(n: int, k: int) → StringExamples
Example 1
n = 3k = 3return = "1/8"Three tosses give 2^3 = 8 equally likely sequences, and only one of them, all heads, has exactly 3 heads. The probability is 1/8.
Example 2
n = 5k = 2return = "5/16"There are 2^5 = 32 equally likely sequences. A sequence with exactly 2 heads is fixed by choosing which 2 of the 5 tosses are heads, and there are 10 such choices. So the probability is 10/32, which is 5/16 in lowest terms.
Example 3
n = 6k = 1return = "3/32"The one head can be any of the 6 tosses, so 6 of the 2^6 = 64 sequences have exactly one head. 6/64 reduces to 3/32.
Constraints
1 <= n <= 500 <= k <= n
More Bank of America Onsite Interview questions
- Centered Star PyramidONSITE INTERVIEW · Seen Nov 2025
- Employees Without a ManagerONSITE INTERVIEW · Seen Nov 2025
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2025
- N-th Fibonacci NumberONSITE INTERVIEW · Seen Nov 2025
- Reverse Each Word in a SentenceONSITE INTERVIEW · Seen Nov 2025
- Second Highest SalaryONSITE INTERVIEW · Seen Nov 2025
- Three Numbers That Add Up to a TargetONSITE INTERVIEW · Seen Apr 2025
- Duplicate RowsONSITE INTERVIEW · Seen Oct 2023
- Factorial of a NumberONSITE INTERVIEW · Seen Oct 2023
- Palindrome String CheckONSITE INTERVIEW · Seen Sep 2023
Similar questions at other companies
- Count Staircases with Strictly Increasing StepseBay · ONSITE INTERVIEWeBay interview questions
- Unique Digit Permutations Without Leading ZeroMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- K-th Amount a Payout Machine Can GiveRippling · ONSITE INTERVIEWRippling interview questions
- Share Items So One Person Gets the MostExpedia · ONSITE INTERVIEWExpedia interview questions
- Enough Muffins for the LineSusquehanna International Group (SIG) · OASusquehanna International Group (SIG) interview questions
- Biased Coin: Probability of Exactly h HeadsAkuna Capital · PHONE SCREENAkuna Capital interview questions
- Revolver: Will the Next Shot Fire?Tower Research Capital · PHONE SCREEN
- Probability of Consecutive HeadsSquarepoint Capital · PHONE SCREENSquarepoint Capital interview questions
- Next Pascal Row CoefficientIntuit · OAIntuit interview questions
- Expected Fake-Name CollisionsMercor · PHONE SCREENMercor interview questions