The input “nums” is supposed to be an array of unique integers ranging from 1 to nums.length. However there is a mistake: one of the number in the array is duplicated, which means another number is missing. Find and return the sum of the duplicated number and the missing number. Example: In the array [4, 3, 3, 1], 3 is present twice and 2 is missing so 3 + 2 = 5 should be returned.


Points to remember before solving

  • The range of the array should be 1 to the length of the array. That means if the length of the array is 5 then the elements will be [1, 2, 3, 4, 5].
  • One number is duplicated with another number.  Example: [2, 2, 3, 4, 5]
  • Find the missing number and also duplicated number.

 

Lets start…


Input:  [1, 2, 3, 4, 5, 5, 7]

Output: 11

Reason: Missing value in the array is 6 and the duplicate value in the array is 5. So the sum of these two numbers will be 11

 

Input: [2, 2, 3, 4, 5, 6]

Output: 3

Reason: Missing value is 1 and duplicated value is 2 in the array. So 1 + 2 = 3.

 


 

JavaScript Code: 

// JavaScript Code

function sum_missing_duplicated(arr) {
    // sort the array first
    let sorted = arr.sort((a, b) => a - b)
    // declaring two variables
    let missing, repeated

    // loop to iterate the array
    for (let i = 0; i < sorted.length; i++) {
        let item = sorted[i];
        if( !arr.includes(i + 1)){
            missing = i + 1
        }
        for (let j = i; j < sorted.length; j++) {
            if (item === sorted[j + 1]) repeated = sorted[i];
        }
    }
    return missing + repeated
}

// --------------------------

let myArray = [1, 2, 3, 3, 5, 6];
console.log("Answer is: " + sum_missing_duplicated(myArray));

 

Output:

Answer is: 7


 

Python Code: 

// Python Code

def sum_missing_duplicated(arr):
    arr.sort() # sort the list first
    missing = 0
    repeated = 0

    # Iterate from first index to last index
    for i in range(0, len(arr)):
        item = arr[i]
        isexist = False

        if not i + 1 in arr:
            missing = i + 1

        for j in range(i, len(arr) - 1):
            if item == arr[j + 1]:
                repeated = arr[i]
                
    return missing + repeated

# -------------------------

mylist = [1, 2, 2, 4, 5]
print("Answer is: " + str(sum_missing_duplicated(mylist)))

 

Output:

Answer is: 5

 


 

You can comment your own code in the comment box…

Leave a Reply

Your email address will not be published.