Find missing number from first N natural numbers.

Question: Find the missing number in first n Natural numbers…

// Approach 1: Using Summation
// TC:O(n)
// SC:O(1)
func findMissingNumber1(arr: [Int]) ->Int {
    let len = arr.count + 1
    var summationOfFirstN = len*(len+1)/2
    for value in arr {
        summationOfFirstN -= value
    }
    return summationOfFirstN
}

// Approach 2: Using Summation
// TC:O(n)
// SC:O(1)
//To avoid integer overflow, pick one number from the range [1, N] and subtract a number from the given array (don’t subtract the same number twice)

func findMissingNumber2(arr: [Int]) ->Int {
    var total: Int = 1
    var arrCount = arr.count + 1
 
    for i in 2..<arrCount {
        total += i;
        total = total - arr[i - 2];
    }
    return total;
}

// Approach 3: Using XOR
// TC:O(2n)
// SC:O(1)
func findMissingNumber3(arr: [Int]) ->Int {

    var arrCount = arr.count
    // For xor of all the elements in array
    var x1 = arr[0];
 
    // For xor of all the elements from 1 to n+1
    var x2 = 1;
 
    for i in 1..<arrCount-1 {
        x1 = x1 ^ arr[i]
    }
    for i in 2..<arrCount+1 {
        x2 = x2 ^ i
    }
    return x1 ^ x2
}
 var arrayMiss: [Int] = [1,2,3,5]
print("Missing numbers is-->", findMissingNumber1(arr: arrayMiss))// 4
print("Missing numbers is-->", findMissingNumber2(arr: arrayMiss))// 4
print("Missing numbers is-->", findMissingNumber3(arr: arrayMiss))//4

Leave a Comment

Your email address will not be published. Required fields are marked *