Leetcode #1467: Probability of a Two Boxes Having The Same Number of Distinct Balls
In this guide, we solve Leetcode #1467 Probability of a Two Boxes Having The Same Number of Distinct Balls in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Math, Dynamic Programming, Backtracking, Combinatorics, Probability and Statistics
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: balls = [1,1]
Output: 1.00000
Explanation: Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
Python Solution
class Solution:
def getProbability(self, balls: List[int]) -> float:
def dfs(i: int, j: int, diff: int) -> float:
if i >= k:
return 1 if j == 0 and diff == 0 else 0
if j < 0:
return 0
ans = 0
for x in range(balls[i] + 1):
y = 1 if x == balls[i] else (-1 if x == 0 else 0)
ans += dfs(i + 1, j - x, diff + y) * comb(balls[i], x)
return ans
n = sum(balls) >> 1
k = len(balls)
return dfs(0, n, 0) / comb(n << 1, n)
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.