Skip to Content

Find Missing Observations

Home | Coding Interviews | Arrays and Strings | Find Missing Observations

You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls.

You are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n.

Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array.

The average value of a set of k numbers is the sum of the numbers divided by k.

Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m.

class Solution {
    public int[] missingRolls(int[] rolls, int mean, int n) {
        int knownRollTotal = 0;
        for (int roll : rolls) {
            knownRollTotal += roll;
        }
        int meanRollTotal = mean * (n + rolls.length);
        int nRollTotal = meanRollTotal - knownRollTotal;
        if (nRollTotal < n || nRollTotal > 6 * n) {
            return new int[] {};
        }
        int val = nRollTotal / n;
        int extra = nRollTotal % n;
        int[] res = new int[n];
        for (int i = 0; i < res.length; i++) {
            res[i] = val + (i < extra ? 1 : 0);
        }
        return res;
    }
}

Posted by grwgreg 9 days ago

Related Problems

You are given a string s. You can convert s to a palindrome by adding characters in front of it.

Return the shortest palindrome you can find by performing this transformation.

Given a string s, find the length of the longest substring without repeating characters.

Given a string S and an integer K, return the length of the longest substring of S that contains at most K distinct characters.

Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.

Return the shortest such subarray and output its length.