#1467

Probability of a Two Boxes Having The Same Number of Distinct Balls

Hard
ArrayMathDynamic ProgrammingBacktrackingCombinatoricsProbability and StatisticsCombinatorial CountingDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of generating all combinations, we can use combinatorial mathematics to calculate the number of valid distributions directly based on the counts of balls of each color. This approach is efficient and avoids redundant calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the total number of ways to choose n balls from 2n balls using combinatorial formulas.
  2. 2Step 2: For each color, determine how many can go into each box while maintaining distinct counts.
  3. 3Step 3: Use dynamic programming to keep track of valid distributions and their probabilities.
  4. 4Step 4: Calculate the final probability of having the same number of distinct colors in both boxes.
solution.py18 lines
1# Full working Python code
2from math import factorial
3
4def probabilitySameDistinct(balls):
5    n = sum(balls) // 2
6    total_ways = factorial(sum(balls)) // (factorial(n) * factorial(sum(balls) - n))
7    same_distinct_count = 0
8
9    def countWays(index, box1_count, box2_count):
10        if index == len(balls):
11            return box1_count == box2_count
12        ways = 0
13        for i in range(min(balls[index], n - box1_count) + 1):
14            ways += countWays(index + 1, box1_count + i, n - box1_count - i)
15        return ways
16
17    same_distinct_count = countWays(0, 0, 0)
18    return same_distinct_count / total_ways

Complexity note: The time complexity is O(n) because we only need to iterate through the colors and calculate combinations without generating all distributions.

  • 1Understanding combinatorial distributions is key to solving this problem efficiently.
  • 2The distinct count of colors can be tracked using combinations rather than brute-force enumeration.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.