Learn-dsa..in 30 days!



























CC-3 : Find missing number in array.

Description:

Given an input integer array arr which is sorted in ascending order and has numbers from 1 to n with one number missing, we need to find the missing number.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={1,3,4,5} 2
arr={1,2,3,4,6} 5

Asked by: , , Leetcode #268

Summary Algorithm:

The algorithm finds a missing number in a sequence from 1 to N by calculating the expected arithmetic sum of all integers up to N and subtracting the actual sum of the elements present in the provided array.

Pseudocode:

The method should accept following input parameters: arr (int array). Input arr should be sorted in ascending order and have numbers from 1 to n with one number missing.
Initialize an int variable n to (arr.length+1), this is because, one number is missing in the array, so n is set to length of array + 1.
Initialize an int variable named sumOfIntegersFrom1ToN and set it to (n*(n+1))/2; (this the mathematical formula for sum of numbers from 1 to n).
Initialize a for loop, iterate through all elements of arr and store sum of all numbers in arr in a variable called sumOfArrayElements.
Since one number is missing, set int variable missingNumber = sumOfIntegersFrom1ToN -sumOfArrayElements.
Return missingNumber.

Code:

public int arrayFindMissingNumberFrom1ToN(int[] arr) throws Exception{
	int n=arr.length+1;
	int sumOfIntegersFrom1ToN= (n*(n+1))/2;
	int sumOfArrayElements=0;
	for (int idx=0; idx < arr.length; idx++) {
		sumOfArrayElements+=arr[idx];
	}
	int missingNumber=sumOfIntegersFrom1ToN-sumOfArrayElements;
	return missingNumber;
}
Time Complexity Space Complexity
O(n) O(1)

Click here for execution trace to understand the code better.

Click here to download and run code and test cases !