Find Two Missing Numbers | Set 1 (An Interesting Linear Time Solution)
Last Updated :
05 Jul, 2022
Given an array of n unique integers where each element in the array is in the range [1, n]. The array has all distinct elements and the size of the array is (n-2). Hence Two numbers from the range are missing from this array. Find the two missing numbers.
Examples :
Input : arr[] = {1, 3, 5, 6}
Output : 2 4
Input : arr[] = {1, 2, 4}
Output : 3 5
Input : arr[] = {1, 2}
Output : 3 4
Method 1 – O(n) time complexity and O(n) Extra Space
Step 1: Take a boolean array mark that keeps track of all the elements present in the array.
Step 2: Iterate from 1 to n, check for every element if it is marked as true in the boolean array, if not then simply display that element.
C++
#include <bits/stdc++.h>
using namespace std;
void findTwoMissingNumbers( int arr[], int n)
{
vector< bool > mark(n+1, false );
for ( int i = 0; i < n-2; i++)
mark[arr[i]] = true ;
cout << "Two Missing Numbers are\n" ;
for ( int i = 1; i <= n; i++)
if (! mark[i])
cout << i << " " ;
cout << endl;
}
int main()
{
int arr[] = {1, 3, 5, 6};
int n = 2 + sizeof (arr)/ sizeof (arr[0]);
findTwoMissingNumbers(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void findTwoMissingNumbers( int arr[], int n)
{
boolean []mark = new boolean [n+ 1 ];
for ( int i = 0 ; i < n- 2 ; i++)
mark[arr[i]] = true ;
System.out.println( "Two Missing Numbers are" );
for ( int i = 1 ; i <= n; i++)
if (! mark[i])
System.out.print(i + " " );
System.out.println();
}
public static void main(String[] args)
{
int arr[] = { 1 , 3 , 5 , 6 };
int n = 2 + arr.length;
findTwoMissingNumbers(arr, n);
}
}
|
Python3
def findTwoMissingNumbers(arr, n):
mark = [ False for i in range (n + 1 )]
for i in range ( 0 ,n - 2 , 1 ):
mark[arr[i]] = True
print ( "Two Missing Numbers are" )
for i in range ( 1 ,n + 1 , 1 ):
if (mark[i] = = False ):
print (i,end = " " )
print ( "\n" )
if __name__ = = '__main__' :
arr = [ 1 , 3 , 5 , 6 ]
n = 2 + len (arr)
findTwoMissingNumbers(arr, n);
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void findTwoMissingNumbers( int []arr, int n)
{
Boolean []mark = new Boolean[n + 1];
for ( int i = 0; i < n - 2; i++)
mark[arr[i]] = true ;
Console.WriteLine( "Two Missing Numbers are" );
for ( int i = 1; i <= n; i++)
if (! mark[i])
Console.Write(i + " " );
Console.WriteLine();
}
public static void Main(String[] args)
{
int []arr = {1, 3, 5, 6};
int n = 2 + arr.Length;
findTwoMissingNumbers(arr, n);
}
}
|
Javascript
<script>
function findTwoMissingNumbers(arr, n)
{
let mark = new Array(n+1);
for (let i = 0; i < n-2; i++)
mark[arr[i]] = true ;
document.write( "Two Missing Numbers are" + "</br>" );
for (let i = 1; i <= n; i++)
if (!mark[i])
document.write(i + " " );
document.write( "</br>" );
}
let arr = [1, 3, 5, 6];
let n = 2 + arr.length;
findTwoMissingNumbers(arr, n);
</script>
|
Output
Two Missing Numbers are
2 4
Method 2 – O(n) time complexity and O(1) Extra Space
The idea is based on this popular solution for finding one missing number. We extend the solution so that two missing elements are printed.
Let’s find out the sum of 2 missing numbers:
arrSum => Sum of all elements in the array
sum (Sum of 2 missing numbers) = (Sum of integers from 1 to n) - arrSum
= ((n)*(n+1))/2 – arrSum
avg (Average of 2 missing numbers) = sum / 2;
- One of the numbers will be less than or equal to avg while the other one will be strictly greater than avg. Two numbers can never be equal since all the given numbers are distinct.
- We can find the first missing number as a sum of natural numbers from 1 to avg, i.e., avg*(avg+1)/2 minus the sum of array elements smaller than avg
- We can find the second missing number by subtracting the first missing number from the sum of missing numbers
Consider an example for better clarification
Input : 1 3 5 6, n = 6
Sum of missing integers = n*(n+1)/2 - (1+3+5+6) = 6.
Average of missing integers = 6/2 = 3.
Sum of array elements less than or equal to average = 1 + 3 = 4
Sum of natural numbers from 1 to avg = avg*(avg + 1)/2
= 3*4/2 = 6
First missing number = 6 - 4 = 2
Second missing number = Sum of missing integers-First missing number
Second missing number = 6-2= 4
Below is the implementation of the above idea.
C++
#include <iostream>
using namespace std;
int getSum( int arr[], int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
void findTwoMissingNumbers( int arr[], int n)
{
int sum = (n*(n + 1)) /2 - getSum(arr, n-2);
int avg = (sum / 2);
int sumSmallerHalf = 0, sumGreaterHalf = 0;
for ( int i = 0; i < n-2; i++)
{
if (arr[i] <= avg)
sumSmallerHalf += arr[i];
else
sumGreaterHalf += arr[i];
}
cout << "Two Missing Numbers are\n" ;
int totalSmallerHalf = (avg*(avg + 1)) / 2;
int smallerElement = totalSmallerHalf - sumSmallerHalf;
cout << smallerElement << " " ;
cout << sum - smallerElement;
}
int main()
{
int arr[] = {1, 3, 5, 6};
int n = 2 + sizeof (arr)/ sizeof (arr[0]);
findTwoMissingNumbers(arr, n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int getSum( int arr[], int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum += arr[i];
return sum;
}
static void findTwoMissingNumbers( int arr[],
int n)
{
int sum = (n * (n + 1 )) /
2 - getSum(arr, n - 2 );
int avg = (sum / 2 );
int sumSmallerHalf = 0 ,
sumGreaterHalf = 0 ;
for ( int i = 0 ; i < n - 2 ; i++)
{
if (arr[i] <= avg)
sumSmallerHalf += arr[i];
else
sumGreaterHalf += arr[i];
}
System.out.println( "Two Missing " +
"Numbers are" );
int totalSmallerHalf = (avg *
(avg + 1 )) / 2 ;
System.out.println(totalSmallerHalf -
sumSmallerHalf);
System.out.println(((n * (n + 1 )) / 2 -
totalSmallerHalf) -
sumGreaterHalf);
}
public static void main (String[] args)
{
int arr[] = { 1 , 3 , 5 , 6 };
int n = 2 + arr.length;
findTwoMissingNumbers(arr, n);
}
}
|
Python3
def getSum(arr,n):
sum = 0 ;
for i in range ( 0 , n):
sum + = arr[i]
return sum
def findTwoMissingNumbers(arr, n):
sum = ((n * (n + 1 )) / 2 -
getSum(arr, n - 2 ));
avg = ( sum / 2 );
sumSmallerHalf = 0
sumGreaterHalf = 0 ;
for i in range ( 0 , n - 2 ):
if (arr[i] < = avg):
sumSmallerHalf + = arr[i]
else :
sumGreaterHalf + = arr[i]
print ( "Two Missing Numbers are" )
totalSmallerHalf = (avg * (avg + 1 )) / 2
print ( str (totalSmallerHalf -
sumSmallerHalf) + " " )
print ( str (((n * (n + 1 )) / 2 -
totalSmallerHalf) -
sumGreaterHalf))
arr = [ 1 , 3 , 5 , 6 ]
n = 2 + len (arr)
findTwoMissingNumbers(arr, n)
|
C#
using System;
class GFG
{
static int getSum( int []arr, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
static void findTwoMissingNumbers( int []arr,
int n)
{
int sum = (n * (n + 1)) / 2 -
getSum(arr, n - 2);
int avg = (sum / 2);
int sumSmallerHalf = 0,
sumGreaterHalf = 0;
for ( int i = 0; i < n - 2; i++)
{
if (arr[i] <= avg)
sumSmallerHalf += arr[i];
else
sumGreaterHalf += arr[i];
}
Console.WriteLine( "Two Missing " +
"Numbers are " );
int totalSmallerHalf = (avg *
(avg + 1)) / 2;
Console.WriteLine(totalSmallerHalf -
sumSmallerHalf);
Console.WriteLine(((n * (n + 1)) / 2 -
totalSmallerHalf) -
sumGreaterHalf);
}
static public void Main ()
{
int []arr = {1, 3, 5, 6};
int n = 2 + arr.Length;
findTwoMissingNumbers(arr, n);
}
}
|
PHP
<?php
function getSum( $arr , $n )
{
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
$sum += $arr [ $i ];
return $sum ;
}
function findTwoMissingNumbers( $arr , $n )
{
$sum = ( $n * ( $n + 1)) /2 -
getSum( $arr , $n - 2);
$avg = ( $sum / 2);
$sumSmallerHalf = 0;
$sumGreaterHalf = 0;
for ( $i = 0; $i < $n - 2; $i ++)
{
if ( $arr [ $i ] <= $avg )
$sumSmallerHalf += $arr [ $i ];
else
$sumGreaterHalf += $arr [ $i ];
}
echo "Two Missing Numbers are\n" ;
$totalSmallerHalf = ( $avg * ( $avg + 1)) / 2;
echo ( $totalSmallerHalf -
$sumSmallerHalf ) , " " ;
echo ((( $n * ( $n + 1)) / 2 - $totalSmallerHalf ) -
$sumGreaterHalf );
}
$arr = array (1, 3, 5, 6);
$n = 2 + sizeof( $arr );
findTwoMissingNumbers( $arr , $n );
?>
|
Javascript
<script>
function getSum(arr, n)
{
let sum = 0;
for (let i = 0; i < n; i++)
sum += arr[i];
return sum;
}
function findTwoMissingNumbers(arr, n)
{
let sum = (n * (n + 1)) / 2 -
getSum(arr, n - 2);
let avg = (sum / 2);
let sumSmallerHalf = 0,
sumGreaterHalf = 0;
for (let i = 0; i < n - 2; i++)
{
if (arr[i] <= avg)
sumSmallerHalf += arr[i];
else
sumGreaterHalf += arr[i];
}
document.write(
"Two Missing " + "Numbers are " + "</br>"
);
let totalSmallerHalf = (avg * (avg + 1)) / 2;
document.write(
(totalSmallerHalf - sumSmallerHalf) + " "
);
document.write(
((n * (n + 1)) / 2 - totalSmallerHalf) -
sumGreaterHalf + "</br>"
);
}
let arr = [1, 3, 5, 6];
let n = 2 + arr.length;
findTwoMissingNumbers(arr, n);
</script>
|
Output
Two Missing Numbers are
2 4
Note: There can be overflow issues in the above solution.
In below set 2, another solution that is O(n) time, O(1) space, and doesn’t cause overflow issues is discussed.
Find Two Missing Numbers | Set 2 (XOR based solution)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...