KatInterview

Chance of a Red Majority When Skipping Returned Marbles

Math & Bit ManipulationAuto-graded · 22 test cases
MediumAuto-gradedMath & Bit Manipulationprobabilitycombinatoricshypergeometric

Last updated

Compute a probability for a draw process with discarded-and-returned items by reducing it to a hypergeometric count, ignoring the irrelevant returned category.

A bag holds red red marbles, blue blue marbles, and green green marbles. You pull marbles one at a time, each uniformly at random from what is currently in the bag.

  • If the marble is green, you put it straight back and keep pulling.
  • If the marble is red or blue, you keep it (it does not go back).

You stop as soon as you are holding exactly three marbles, all of them red or blue.

Write a function that returns the probability that at least two of the three marbles you hold are red.

Rules and edge cases

  • Return the probability as a floating-point number.
  • If the bag contains fewer than three non-green marbles in total (red + blue < 3), you can never hold three marbles, so return 0.0.
  • The value of green may be any non-negative integer. Treat the process as one that ends with probability 1 whenever red + blue >= 3.

Constraints

  • 0 <= red, blue, green <= 1000
  • All inputs are integers.
  • The result is compared to the expected value as a float with a small tolerance.

Examples

Example 1

Input: prob_red_majority(5, 5, 5)

Output: 0.5

Example 2

Input: prob_red_majority(10, 5, 5)

Output: 0.7582417582417582

Hints

Hint 1

Think about what a green pull changes. If the marble goes back immediately, does the bag look any different afterwards?

Hint 2

Condition on the pull being non-green: the chance it is red is red / (red + blue), regardless of how many green marbles there are. So the three kept marbles behave like three drawn without replacement from only the red and blue marbles.

Hint 3

Count favorable selections: exactly 3 red, plus exactly 2 red and 1 blue. Divide by the number of ways to choose any 3 of the red and blue marbles. Don't forget the case with fewer than 3 non-green marbles.