VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-one-missing-number-range/

⇱ Find the one missing number in range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the one missing number in range

Last Updated : 28 Oct, 2022

Given an array of size n. It is also given that range of numbers is from smallestNumber to smallestNumber + n where smallestNumber is the smallest number in array. The array contains number in this range but one number is missing so the task is to find this missing number.

Examples: 

Input:  arr[] = {13, 12, 11, 15}
Output:  14

Input:  arr[] = {33, 36, 35, 34};
Output: 37

The problem is very close to find missing number.
There are many approaches to solve this problem. 

A simple approach is to first find minimum, then one by one search all elements. Time complexity of this approach is O(n*n)

A better solution is to sort the array. Then traverse the array and find the first element which is not present. Time complexity of this approach is O(n Log n)

The best solution is to first XOR all the numbers. Then XOR this result to all numbers from smallest number to n+smallestNumber. The XOR is our result.

Example:

arr[n] = {13, 12, 11, 15}
smallestNumber = 11

first find the xor of this array
13^12^11^15 = 5

Then find the XOR first number to first number + n
11^12^13^14^15 = 11;

Then xor these two number's
5^11 = 14 // this is the missing number

Implementation:


Output
14

Time Complexity: O(n), where n is the size of the array
Auxiliary Space: O(1)

Another Approach:

An efficient approach to find out the missing number can be performed using the concept that sum of the arithmetic progression smallestNumber, smallestNumber + 1, smallestNumber + 2, ..... , smallestNumber + n, which is (n + 1) x (2smallestNumber + 1) / 2 is equal to the sum of the array + the missing number.

In other words,

Sum of the AP - Sum of the array = Missing Number.

The advantage of this method is that we can utilize the inbuilt library methods to calculate the sum and minimum number of the array, which will reduce the execution time, especially for languages like Python3 and JavaScript.

Implementation:


Output
14

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment