LeetCode 1467: Probability of a Two Boxes Having The Same Number of Distinct Balls Solution
Master LeetCode problem 1467 (Probability of a Two Boxes Having The Same Number of Distinct Balls), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1467. Probability of a Two Boxes Having The Same Number of Distinct Balls
Problem Explanation
Explanation:
To solve this problem, we need to calculate the probability that two boxes have the same number of distinct balls after distributing the balls randomly. We can approach this by recursively trying all possible distributions of balls to the two boxes and checking if they have the same number of distinct colors.
- We start by generating all possible permutations of the balls.
- For each permutation, we split the balls into two equal halves and count the number of distinct colors in each half.
- If the number of distinct colors in both halves is the same, we increment a counter.
- Finally, we return the ratio of the counter to the total number of permutations as the probability.
Time Complexity: O(n! * n) where n is the total number of balls
Space Complexity: O(n)
:
Solution Code
class Solution {
public double getProbability(int[] balls) {
int sum = 0;
for (int b : balls) {
sum += b;
}
int n = sum / 2; // Total number of balls in each box
return dfs(balls, new int[balls.length], 0, 0, n, n) / perm(sum / 2);
}
private double dfs(int[] balls, int[] cnt, int idx, int sum1, int sum2, int n) {
if (sum1 > n || sum2 > n) return 0;
if (idx == balls.length) {
return sum1 == n && sum2 == n ? 1 : 0;
}
double res = 0;
for (int i = 0; i <= balls[idx]; i++) {
cnt[idx] = i;
res += dfs(balls, cnt, idx + 1, sum1 + i, sum2 + (balls[idx] - i), n);
}
return res;
}
private double perm(int n) {
double res = 1;
for (int i = 1; i <= n; i++) {
res *= i;
}
return res;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1467 (Probability of a Two Boxes Having The Same Number of Distinct Balls)?
This page provides optimized solutions for LeetCode problem 1467 (Probability of a Two Boxes Having The Same Number of Distinct Balls) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1467 (Probability of a Two Boxes Having The Same Number of Distinct Balls)?
The time complexity for LeetCode 1467 (Probability of a Two Boxes Having The Same Number of Distinct Balls) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1467 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1467 in Java, C++, or Python.