LeetCode 2028. Find Missing Observations — JavaScript
var missingRolls = function(rolls, mean, n) {
const rollsSum = rolls.reduce((accu, curr) => accu + curr, 0);
const totalSum = mean * (rolls.length + n);
const rest = totalSum - rollsSum;
// If it's impossible to find a valid solution, return an empty array
if (rest < n || rest > 6 * n) return [];
const baseRoll = Math.floor(rest / n);
const extraRolls = rest % n;
const missingRolls = Array(n).fill(baseRoll);
// Distribute the extra rolls to ensure all values are valid dice rolls
for (let i = 0; i < extraRolls; i++) {
missingRolls[i]++;
}
return missingRolls;
};
Intuition
The problem requires us to find the missing rolls in a series of dice rolls that would result in a specific average when combined with the existing rolls. We know the average and the number of missing rolls, so our first thought is to calculate the total sum that the missing rolls need to add up to in order to achieve the desired mean. Once we have this target sum, we can distribute it among the missing rolls while ensuring each roll is a valid dice number (between 1 and 6).
Approach
- Calculate the Target Sum: First, compute the total sum needed to achieve the desired mean across all rolls (existing and missing).
- Determine the Sum for Missing Rolls: Subtract the sum of the existing rolls from the target sum to find out how much the missing rolls should add up to.
- Check for Validity: If the sum required for the missing rolls is not achievable with the given number of rolls (i.e., it’s either too small or too large), return an empty array.
- Distribute the Sum: If valid, distribute the target sum evenly across the missing rolls. If there’s any remainder, distribute it by incrementing the minimum rolls one by one until all extra points are allocated.
Complexity
- Time complexity:
The time complexity of this approach is O(n), where n is the number of missing rolls. This is because we iterate over the missing rolls to distribute the values. - Space complexity:
The space complexity is O(n) as well, since we are storing the result in an array of length n for the missing rolls.
Join me and over 40 million users who love Revolut. Sign up with my link below: https://revolut.com/referral/?referral-code=weijhih!AUG2-24-VR-IE-AE