#2028
Find Missing Observations
MediumArrayMathSimulationMathematical calculations for averages.Array manipulation for generating results.
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of generating combinations, we can directly calculate the required missing rolls based on the desired mean. This approach is efficient and straightforward.
⚙️
Algorithm
5 steps- 1Step 1: Calculate the total sum required for n + m rolls: total_sum = mean * (n + m).
- 2Step 2: Calculate the current sum of the given rolls.
- 3Step 3: Determine the sum needed for the missing rolls: missing_sum = total_sum - current_sum.
- 4Step 4: Check if the missing_sum is within the valid range (n to 6 * n). If not, return an empty array.
- 5Step 5: If valid, create an array filled with the average value (missing_sum / n) and adjust the last element to ensure the sum matches missing_sum.
solution.py12 lines
1# Full working Python code
2
3def find_missing_observations(rolls, mean, n):
4 total_sum = mean * (len(rolls) + n)
5 current_sum = sum(rolls)
6 missing_sum = total_sum - current_sum
7 if missing_sum < n or missing_sum > 6 * n:
8 return []
9 missing_obs = [missing_sum // n] * n
10 for i in range(missing_sum % n):
11 missing_obs[i] += 1
12 return missing_obsℹ
Complexity note: This complexity comes from creating the output array of size n and performing constant time calculations.
- 1The average must be an integer, which means the total sum must be divisible by n + m.
- 2The missing observations must be within the range of 1 to 6, as they represent dice rolls.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.