Missing Numbers

  • + 0 comments

    Python 3 Solution

    • We need to find frequencies of elements of both arrays, and store somewhere like element1:frequency, element2:frequency i.e. dictionary or what we call Hash Map in Data Structures. -> This is O(n) operation
    • For every unique element in brr array, we need to check if its frequency count is greater than how many times it appear in arr array. Since dictionary has unique elements as well as freq counts, lets loop over its keys, and compare values with arr's freq count (dictionary values). If greater add it in result list. -> O(n) to loop, comparisons on dict are O(1)
    • sort the result list and return it. -> O(klogk) where k is unique missing elements which will be <= 100.
    • Overall time complexity is around O(n).
    def missingNumbers(arr, brr):
        missing = []
        arrcount = dict()
    		# calculate and store frequency counts for every arr element
        for a in arr:
            if arrcount.get(a):
                arrcount[a] += 1
            else:
                arrcount[a] = 1
    		
        brrcount = dict()
        for b in brr:
            if brrcount.get(b):
                brrcount[b] += 1
            else:
                brrcount[b] = 1
    						
        for key in brrcount:
            if brrcount[key]>arrcount.get(key,0):
                missing.append(key)
        return sorted(missing)