Math Fundamentals18 sections · 814 units
Open in Course

Mismatch - Implementation

Frequency array

Here is the solution:


function findErrorNums(nums)
    n := length of nums
    count := array of size (n + 1) initialized to 0
    for each num in nums
        increment count[num]
    duplicate := -1
    missing := -1
    for i from 1 to n
        if count[i] = 2 then
            duplicate := i
        if count[i] = 0 then
            missing := i
    return [duplicate, missing]

You count frequencies, then scan for the duplicate and missing number. Time: O(n)O(n), Space: O(n)O(n).