KatInterview

Probability the Third Card Is an Ace After an Ace Appears

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingprobabilityconditional-probabilitycounting

Last updated

Compute a conditional probability for drawing three cards without replacement by splitting on how many aces the first two draws contain.

A deck holds total_cards distinct cards, of which exactly ace_count are aces. Three cards are drawn uniformly at random, one after another, without replacement (so every ordered triple of distinct cards is equally likely).

Given that at least one of the first two drawn cards is an ace, return the probability that the third drawn card is an ace.

Implement third_ace_given_ace_in_first_two(total_cards, ace_count) and return the conditional probability as a float.

Details:

  • The conditioning event is "the first card is an ace OR the second card is an ace" (possibly both). Everything is computed relative to that event, not to the unconditioned deck.
  • Returns 0.0 when the third card cannot possibly be an ace under the condition (for example, a deck with a single ace).
  • Answers are compared with a small floating-point tolerance, so any correct evaluation order is fine.
Constraints
  • 3 <= total_cards <= 10**6
  • 1 <= ace_count <= total_cards
  • The conditioning event always has positive probability, so the conditional probability is well defined.

Examples

Example 1

Input: third_ace_given_ace_in_first_two(52, 4)

Output: 0.0593939393939394

Example 2

Input: third_ace_given_ace_in_first_two(3, 1)

Output: 0

Example 3

Input: third_ace_given_ace_in_first_two(4, 2)

Output: 0.39999999999999997

Hints

Hint 1

Split the conditioning event into two mutually exclusive cases: exactly one ace among the first two cards, and exactly two aces among the first two cards.

Hint 2

If the first two cards contain exactly one ace, an ace is left among the `total_cards - 2` unseen cards; if they contain two aces, one fewer ace remains.

Hint 3

Weight each case by its probability *given* that at least one ace is already in the first two cards, and count the two-case probabilities from the number of unordered pairs.