Missing Numbers

Sort by

recency

|

1257 Discussions

|

  • + 0 comments

    Here is solution in python, java, c++ and c programming - https://programmingoneonone.com/hackerrank-missing-numbers-problem-solution.html

  • + 0 comments

    Java Simple Solution using TreeMap

    public static List<Integer> missingNumbers(List<Integer> arr, List<Integer> brr) {
        Map<Integer,Long> map1 = arr.stream().collect(Collectors.groupingBy(Function.identity(),TreeMap::new,Collectors.counting()));
        
        Map<Integer,Long> map2 = brr.stream().collect(Collectors.groupingBy(Function.identity(),TreeMap::new,Collectors.counting()));
        
        List<Integer> answer = new ArrayList<>();
        for(Integer key : map2.keySet()){
            if(map1.containsKey(key)){
                if(map1.get(key) < map2.get(key)){
                    answer.add(key);
                }
            }
            else{
                answer.add(key);
            }
        }
        return answer;
        }
    }
    
  • + 0 comments
    vector<int> missingNumbers(vector<int> arr, vector<int> brr) {
        int mn = *min_element(brr.begin(), brr.end());
        int mx = *max_element(brr.begin(), brr.end());
        vector<int> freq(mx - mn + 1, 0);
        for (int x : brr) freq[x - mn]++;
        for (int x : arr) freq[x - mn]--;
        vector<int> ans;
        for (int i = 0; i < freq.size(); i++)
            if (freq[i] != 0)
                ans.push_back(i + mn);
    
        return ans;
    }
    
  • + 0 comments

    JS solution using reduce. EZ

    function missingNumbers(arr, brr) {
        
        const groupA = arr.reduce((acc, n) => {
            acc[n] = (acc[n] || 0) + 1;
            return acc;
        }, {});
        
        const groupB = brr.reduce((acc, n) => {
            acc[n] = (acc[n] || 0) + 1;
            return acc;
        }, {});
        
        var missing = [];
        for(const nu of brr){
            if(groupA[nu] !== groupB[nu] && missing.indexOf(nu) < 0){
                missing.push(nu);
            }
        }
       
        return missing.sort(function(a, b) {
            return a - b;
        });
    }
    
  • + 0 comments

    Counting Sort is your friend, and the answer to many problems of this nature.

    O(m + n) solution is the goal.