Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Hiring!

Courses Tutorials Jobs Practice Contests Sign In


Sign in to GeeksforGeeks with Google
Mega Hiring Challenge DSA Data Structures Algorithms Interview Preparation Data Science Topic-wise Practice C++ Java
Madhusudhan
Write an Article pmadhusudhanit@gmail.com

Write an Interview Find the Missing Number Madhu Sudhan


pasupulatimadhu96@gmail.com
Experience
Difficulty Level :
Easy ● Last Updated :
09 Dec, 2022
1 more account
Possible to form a
triangle from array
values Read Discuss(470+) Courses Practice Video

Count the number of


possible triangles
Given an array arr[] of size N-1 with integers in the range of

Find the Missing


Number
[1, N], the task is to find the missing number from the first N

integers.

Search an element in a
sorted and rotated
Note : There are no duplicates in the list.

Array Examples : 

Find if there is a pair


with a given sum in the Input : arr[] = {1, 2, 4, 6, 3, 7, 8}, N = 8

rotated sorted Array


Output : 5

Find maximum value of Explanation: The missing number between 1 to 8 is 5

Sum( i*arr[i]) with only


rotations on given array
allowed

Maximum sum of i*arr[i]


among all rotations of a
given array

Find the Rotation Count


in Rotated Sorted array

Quickly find multiple left


rotations of an array |
Set 1
Input : arr[] = {1, 2, 3, 5}, N = 5

Find the Minimum


element in a Sorted and Output : 4

Rotated Array Explanation: The missing number between 1 to 5 is 4

Reversal algorithm for


right rotation of an
array
Recommended Problem

Find a rotation with Missing number in array


maximum hamming Arrays Bit Magic +3 more Solve Problem

distance Accolite Adobe +11 more


Submission count:
6.8L

Skip to content
Start Your Coding Journey Now! Login Register
Sign in to GeeksforGeeks with Google

Madhusudhan
pmadhusudhanit@gmail.com

Madhu Sudhan
pasupulatimadhu96@gmail.com

1 more account

Approach 1 (Using Hashing): The idea behind the following

approach is

The numbers will be in the range (1, N), an array of

size N can be maintained to keep record of the

element s present in the given array

Create a temp array temp[] of size n + 1 with all initial

values as 0.

Traverse the input array arr[], and do following for each

arr[i] 

if(temp[arr[i]] == 0) temp[arr[i]] = 1 

Traverse temp[] and output the array element having

value as 0 (This is the missing element).

Below is the implementation of the above approach:

C++

// C++ program to Find the missing element


 
#include <bits/stdc++.h>
using namespace std;
 
void findMissing(int arr[], int N)
{
    int i;
    int temp[N + 1];
    for(int i = 0; i <= N; i++){
      temp[i] = 0;
    }
   
    for(i = 0; i < N; i++){
      temp[arr[i] - 1] = 1;
    }
 
 
    int ans;
    for (i = 0; i <= N ; i++) {
        if (temp[i] == 0)
            ans =Skip
i  to
+ content
1;
    }
Start Your Coding
    cout Journey
}
<< ans; Now! Login Register
Sign in to GeeksforGeeks with Google
 
/* Driver code */
int main() Madhusudhan
{ pmadhusudhanit@gmail.com

    int arr[] = { 1, 3, 7, 5, 6, 2 };
Madhu Sudhan
    int n = sizeof(arr) / sizeof(arr[0]);
    findMissing(arr, n); pasupulatimadhu96@gmail.com
}
1 more account

#include <stdio.h>
 
void findMissing(int arr[], int N)
{
    int temp[N + 1];
    for (int i = 0; i <= N; i++) {
        temp[i] = 0;
    }
 
    for (int i = 0; i < N; i++) {
        temp[arr[i] - 1] = 1;
    }
 
    int ans;
    for (int i = 0; i <= N; i++) {
        if (temp[i] == 0)
            ans = i + 1;
    }
    printf("%d", ans);
}
 
/* Driver code */
int main()
{
    int arr[] = { 1, 3, 7, 5, 6, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    findMissing(arr, n);
}
 
// This code is contributed by nikhilm2302

Java

// Java code to implement the approach


import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find the missing number
    public static void findMissing(int arr[],
    {
        int i;
        int temp[] = new int[N + 1];
        for (i = 0; i <= N; i++) {
            temp[i] = 0;
        }
 
        for (i = 0; i < N; i++) {
Skip to content
            temp[arr[i] - 1] = 1;
        }
Start Your Coding
  Journey Now!
        int ans = 0;
Login Register
Sign in to GeeksforGeeks with Google
        for (i = 0; i <= N; i++) {
            if (temp[i] == 0)
                ans = i + 1; Madhusudhan
        } pmadhusudhanit@gmail.com

        System.out.println(ans);
    } Madhu Sudhan
    // Driver Code pasupulatimadhu96@gmail.com
    public static void main(String[] args)
    { 1 more account
        int arr[] = { 1, 3, 7, 5, 6, 2 };
        int n = arr.length;
 
        // Function call
        findMissing(arr, n);
    }
}

P ython3

# Find Missing Element


def findMissing(arr, N):
   
    # create a list of zeroes
    temp = [0] * (N+1)
 
    for i in range(0, N):
        temp[arr[i] - 1] = 1
 
    for i in range(0, N+1):
        if(temp[i] == 0):
            ans = i + 1
 
    print(ans)
 
# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3, 5]
    N = len(arr)
 
    # Function call
    findMissing(arr, N)
 
    # This code is contributed by nikhilm2302

C#

using System;
public class GFG {
 
  public static void findMissing(int[] arr, in
  {
     
    // this will create a new array containing
    int[] temp = new int[N + 1];
 
    for (int i = 0; i < N; i++) {
      temp[arr[i] - 1] = 1;
    }
 
    int ans = 0;
    for (int i = Skip
0; ito<=
content
N; i++) {
      if (temp[i] == 0)
Start Your Coding Journey
        ans
    }
Now!
= i + 1; Login Register
Sign in to GeeksforGeeks with Google
    Console.WriteLine(ans);
  }
  static public void Main() Madhusudhan
  { pmadhusudhanit@gmail.com
    int[] arr = { 1, 3, 7, 5, 6, 2 };
    int n = arr.Length; Madhu Sudhan
  pasupulatimadhu96@gmail.com
    findMissing(arr, n);
  } 1 more account
}
 
// This code is contributed by nikhilm2302.

Javascript

// Javascript code to implement the approach


 
// Function to find the missing number
function findMissing(arr,N){
  let i;
  let temp = [];
  for (i = 0; i <= N; i++) {
            temp[i] = 0;
        }
 
        for (i = 0; i < N; i++) {
            temp[arr[i] - 1] = 1;
        }
 
        let ans = 0;
        for (i = 0; i <= N; i++) {
            if (temp[i] == 0)
                ans = i + 1;
        }
        console.log(ans);
}
 
// Driver code
        let arr = [ 1, 3, 7, 5, 6, 2 ];
        let n = arr.length;
 
        // Function call
       findMissing(arr,n);
 
 

Output

Time Complexit y: O(N)

Auxiliar y Space : O(N)

Approach 2 (Using summation of first N natural numbers):

The idea behind the approach is to use the summation of the

first N numbers.

Skip to content
Start Your Coding Journey Now! Login
Find the sum of the numbers in the range [1, N] using
Register
Sign in to GeeksforGeeks with Google
the formula N * (N+1)/2. Now find the sum of all the

Madhusudhan
element s in the array and subtract it from the sum of

pmadhusudhanit@gmail.com
the first N natural numbers. This will give the value of

the missing element.


Madhu Sudhan
pasupulatimadhu96@gmail.com

1 more account

Follow the steps mentioned below to implement the idea:

Calculate the sum of the first N natural numbers as

sumtotal= N*(N+1)/2.

Traverse the array from star t to end.

Find the sum of all the array element s.

Print the missing number as SumTotal – sum of array

Below is the implementation of the above approach:

C++14

#include <bits/stdc++.h>
using namespace std;
 
// Function to get the missing number
int getMissingNo(int a[], int n)
{
    // Given the range of elements
    // are 1 more than the size of array
    int N = n + 1;
   
    int total = (N) * (N + 1) / 2;
    for (int i = 0; i < n; i++)
        total -= a[i];
    return total;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
   
    // Function call
    int miss = getMissingNo(arr, N);
    cout << miss;
    return 0;
}

#include <stdio.h>
 
// Function to find the missing number
int getMissingNo(int a[], int n)
{
    int i, total;
    total = (n + 1) * (n + 2) / 2;
Skip to content
    for (i = 0; i < n; i++)
Start Your Coding Journey
        total Now!
-= a[i];
    return total;
Login Register
Sign in to GeeksforGeeks with Google
}
 
// Driver code Madhusudhan
void main() pmadhusudhanit@gmail.com

{
    int arr[] = { 1, 2, 3, 5 }; Madhu Sudhan
pasupulatimadhu96@gmail.com
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call 1 more account
    int miss = getMissingNo(arr, N);
    printf("%d", miss);
}

Java

// Java program to find missing Number


 
import java.util.*;
import java.util.Arrays;
 
class GFG {
 
    // Function to find the missing number
    public static int getMissingNo(int[] nums,
    {
        int sum = ((n + 1) * (n + 2)) / 2;
        for (int i = 0; i < n; i++)
            sum -= nums[i];
        return sum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 5 };
        int N = arr.length;
        System.out.println(getMissingNo(arr, N
    }
}

P ython

# Function to find the missing element


def getMissingNo(arr, n):
    total = (n + 1)*(n + 2)/2
    sum_of_A = sum(arr)
    return total - sum_of_A
 
# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3, 5]
    N = len(arr)
     
    # Function call
    miss = getMissingNo(arr, N)
    print(miss)
     
# This code is contributed by Pratik Chhajer

Skip to content
Start Your Coding Journey Now!
C# Login Register
Sign in to GeeksforGeeks with Google
// C# program to find missing Number
using System; Madhusudhan
  pmadhusudhanit@gmail.com
class GFG {
    // Function to find missing number Madhu Sudhan
    static int getMissingNo(int[] a, intpasupulatimadhu96@gmail.com
n)
    {
        int total = (n + 1) * (n + 2) / 2;
1 more account
 
        for (int i = 0; i < n; i++)
            total -= a[i];
 
        return total;
    }
 
    /* program to test above function */
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 5 };
        int N = 4;
        int miss = getMissingNo(arr, N);
        Console.Write(miss);
    }
}
 
// This code is contributed by Sam007_

PHP

<?php
// PHP program to find
// the Missing Number
 
// getMissingNo takes array and
// size of array as arguments
function getMissingNo ($a, $n)
{
    $total = ($n + 1) * ($n + 2) / 2;
    for ( $i = 0; $i < $n; $i++)
        $total -= $a[$i];
    return $total;
}
 
// Driver Code
$arr = array(1, 2, 3, 5);
$N = 4;
$miss = getMissingNo($arr, $N);
echo($miss);
 
// This code is contributed by Ajit.
?>

Javascript

  
    // Function to get the missing number
    function getMissingNo(a, n) {
  
        let total = Math.floor((n + 1) * (n +
        for (let i = 0; i < n; i++)
Skip to content
            total -= a[i];
Start Your Coding Journey
        return
    }
Now!
total; Login Register
Sign in to GeeksforGeeks with Google
  
    // Driver Code
  Madhusudhan
    let arr = [ 1, 2, 3, 5 ]; pmadhusudhanit@gmail.com
    let N = arr.length;
    let miss = getMissingNo(arr, N); Madhu Sudhan
    document.write(miss); pasupulatimadhu96@gmail.com
 
// This code is contributed by Surbhi Tyagi 1 more account
 

Output

Time Complexit y: O(N)

Auxiliar y Space : O(1)

Modification for Over flow: The approach remains the same

but there can be an over flow if N is large. 

In order to avoid integer over flow, pick one number

from the range [1, N] and subtract a number from the

given array (don’t subtract the same number twice).

This way there won’t be any integer over flow.

Algorithm: 

Create a variable sum = 1 which will store the missing

number and a counter variable c = 2.

Traverse the array from star t to end.

Update the value of sum as sum = sum – array[i] + c

and increment c by 1. This per forms the task

mentioned in the above idea]

Print the missing number as a sum.

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>
using namespace std;
 
// Function to get the missing element
int getMissingNo(int a[], int n)
{
    int i, total = 1;
 
    for (i = 2; i <= (n + 1); i++) {
        total += i;
        total -= Skip
a[i to
- content
2];
    }
Start Your Coding Journey
    return
}
total; Now! Login Register
Sign in to GeeksforGeeks with Google
 
// Driver Program
int main() Madhusudhan
{ pmadhusudhanit@gmail.com

    int arr[] = { 1, 2, 3, 5 };
Madhu Sudhan
    int N = sizeof(arr) / sizeof(arr[0]);
    pasupulatimadhu96@gmail.com
    // Function call
    cout << getMissingNo(arr, N); 1 more account
    return 0;
}
 
// This code is contributed by Aditya Kumar (a

#include <stdio.h>
 
// Function to get the missing element
int getMissingNo(int a[], int n)
{
    int i, total = 1;
 
    for (i = 2; i <= (n + 1); i++) {
        total += i;
        total -= a[i - 2];
    }
    return total;
}
 
// Driver code
void main()
{
    int arr[] = { 1, 2, 3, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    printf("%d", getMissingNo(arr, N));
}
// This code is contributed by Aditya Kumar (a

Java

// Java implementation
class GFG {
   
    // Function to get the missing number
    static int getMissingNo(int a[], int n)
    {
        int total = 1;
        for (int i = 2; i <= (n + 1); i++) {
            total += i;
            total -= a[i - 2];
        }
        return total;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 5 };
Skip to content
        int N = arr.length;
       
Start Your Coding Journey
        // Now!
Function call Login
        System.out.println(getMissingNo(arr,
Register
Sign in toNGeeksforGeeks with Google
    }
}
  Madhusudhan
pmadhusudhanit@gmail.com
// This code is contributed by Aditya Kumar (a

Madhu Sudhan
pasupulatimadhu96@gmail.com
P ython3

1 more account
# Function to get the missing number
def getMissingNo(a, n):
    i, total = 0, 1
 
    for i in range(2, n + 2):
        total += i
        total -= a[i - 2]
    return total
 
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 2, 3, 5]
    N = len(arr)
 
    # Function call
    print(getMissingNo(arr, N))
 
# This code is contributed by Mohit kumar

C#

using System;
 
class GFG {
 
    // Function to find the missing number
    static int getMissingNo(int[] a, int n)
    {
        int i, total = 1;
 
        for (i = 2; i <= (n + 1); i++) {
            total += i;
            total -= a[i - 2];
        }
        return total;
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 5 };
        int N = (arr.Length);
       
        // Function call
        Console.Write(getMissingNo(arr, N));
    }
}
// This code is contributed by SoumikMondal

Javascript

Skip to content
 
Start Your Coding JourneytheNow!
// a represents array
// n : Number of elements in array a
Login Register
Sign in to GeeksforGeeks with Google
function getMissingNo(a, n)
{
    let i, total=1; Madhusudhan
      pmadhusudhanit@gmail.com

    for (i = 2; i<= (n+1); i++)


    { Madhu Sudhan
        total += i; pasupulatimadhu96@gmail.com
        total -= a[i-2];
    } 1 more account
    return total;
}
 
//Driver Program
    let arr = [1, 2, 3, 5];
    let N = arr.length;
     
    // Function call
    document.write(getMissingNo(arr, N));
 
 
//This code is contributed by Mayank Tyagi
 

Output

Time Complexit y: O(N).  Only one traversal of the array is

needed.

Auxiliar y Space : O(1). No extra space is needed

Approach 3 (Using binar y operations): This method uses

the technique of XOR to solve the problem.  

XOR has cer tain proper ties 

A ssume a1 ⊕a ⊕a ⊕...⊕a
2 3 n
= a and a1 ⊕a ⊕a
2 3

⊕...⊕a n-1
= b

Then a ⊕b=a n

Follow the steps mentioned below to implement the idea:

Create two variables a = 0 and b = 0

Run a loop from i = 1 to N:

For ever y index, update a as a = a ^ i

Now traverse the array from i = star t to end.

For ever y index, update b as b = b ^ arr[i].

The missing number is a ^ b.

Skip to content
Below is the implementation of the above approach:
Start Your Coding Journey Now!
C++ Login Register
Sign in to GeeksforGeeks with Google
#include <bits/stdc++.h>
using namespace std; Madhusudhan
  pmadhusudhanit@gmail.com
// Function to get the missing number
int getMissingNo(int a[], int n) Madhu Sudhan
{ pasupulatimadhu96@gmail.com
    // For xor of all the elements in array
    int x1 = a[0];
1 more account
 
    // For xor of all the elements from 1 to n
    int x2 = 1;
 
    for (int i = 1; i < n; i++)
        x1 = x1 ^ a[i];
 
    for (int i = 2; i <= n + 1; i++)
        x2 = x2 ^ i;
 
    return (x1 ^ x2);
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
   
    // Function call
    int miss = getMissingNo(arr, N);
    cout << miss;
    return 0;
}

#include <stdio.h>
 
// Function to find the missing number
int getMissingNo(int a[], int n)
{
    int i;
 
    // For xor of all the elements in array
    int x1 = a[0];
 
    // For xor of all the elements from 1 to n
    int x2 = 1;
 
    for (i = 1; i < n; i++)
        x1 = x1 ^ a[i];
 
    for (i = 2; i <= n + 1; i++)
        x2 = x2 ^ i;
 
    return (x1 ^ x2);
}
 
// Driver code
void main()
{
    int arr[] = { 1, 2, 3, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
Skip to content
 
Start Your Coding Journeycall
    // Function Now! Login
    int miss = getMissingNo(arr, N);
Register
Sign in to GeeksforGeeks with Google
    printf("%d", miss);
}
Madhusudhan
pmadhusudhanit@gmail.com

Java Madhu Sudhan


pasupulatimadhu96@gmail.com

// Java program to find missing Number


// using xor 1 more account
 
class Main {
 
    // Function to find missing number
    static int getMissingNo(int a[], int n)
    {
        int x1 = a[0];
        int x2 = 1;
 
        // For xor of all the elements in arra
        for (int i = 1; i < n; i++)
            x1 = x1 ^ a[i];
 
        // For xor of all the elements from 1
        for (int i = 2; i <= n + 1; i++)
            x2 = x2 ^ i;
 
        return (x1 ^ x2);
    }
 
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 1, 2, 3, 5 };
        int N = arr.length;
 
        // Function call
        int miss = getMissingNo(arr, N);
        System.out.println(miss);
    }
}

P ython3

# Python3 program to find


# the missing Number
# getMissingNo takes list as argument
 
 
def getMissingNo(a, n):
    x1 = a[0]
    x2 = 1
 
    for i in range(1, n):
        x1 = x1 ^ a[i]
 
    for i in range(2, n + 2):
        x2 = x2 ^ i
 
    return x1 ^ x2
 
 
# Driver program to test above function
Skip to content
if __name__ == '__main__':
 
Start Your Coding
    arr =Journey Now!
[1, 2, 3,
    N = len(arr)
5] Login Register
Sign in to GeeksforGeeks with Google
 
    # Driver code
    miss = getMissingNo(arr, N) Madhusudhan
    print(miss) pmadhusudhanit@gmail.com
 
Madhu Sudhan
# This code is contributed by Yatin Gupta
pasupulatimadhu96@gmail.com

1 more account
C#

// C# program to find missing Number


// using xor
using System;
 
class GFG {
    // Function to find missing number
    static int getMissingNo(int[] a, int n)
    {
        int x1 = a[0];
        int x2 = 1;
 
        // For xor of all the elements in arra
        for (int i = 1; i < n; i++)
            x1 = x1 ^ a[i];
 
        // For xor of all the elements from 1
        for (int i = 2; i <= n + 1; i++)
            x2 = x2 ^ i;
 
        return (x1 ^ x2);
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 5 };
        int N = 4;
       
        // Function call
        int miss = getMissingNo(arr, N);
        Console.Write(miss);
    }
}
 
// This code is contributed by Sam007_

PHP

<?php
// PHP program to find
// the Missing Number
// getMissingNo takes array and
// size of array as arguments
function getMissingNo($a, $n)
{
    // For xor of all the
    // elements in array
    $x1 = $a[0];
     
    // For xor of all the
    // elements from 1 to n + 1
    $x2 = 1; Skip to content
     
Start Your Coding Journey
    for ($i Now!
= 1; $i < $n; $i++)
        $x1 = $x1 ^ $a[$i];
Login Register
Sign in to GeeksforGeeks with Google
             
    for ($i = 2; $i <= $n + 1; $i++)
        $x2 = $x2 ^ $i;     Madhusudhan
      pmadhusudhanit@gmail.com
    return ($x1 ^ $x2);
} Madhu Sudhan
  pasupulatimadhu96@gmail.com
// Driver Code
$arr = array(1, 2, 3, 5); 1 more account
$N = 4;
$miss = getMissingNo($arr, $N);
echo($miss);
 
// This code is contributed by Ajit.
?>

Javascript

      // Function to get the missing number


      function getMissingNo(a, n)
      {
       
        // For xor of all the elements in arra
        var x1 = a[0];
 
        // For xor of all the elements from 1
        var x2 = 1;
        for (var i = 1; i < n; i++) x1 = x1 ^
        for (var i = 2; i <= n + 1; i++) x2 =
 
        return x1 ^ x2;
      }
 
      // Driver Code
 
      var arr = [1, 2, 3, 5];
      var N = arr.length;
      var miss = getMissingNo(arr, N);
      document.write(miss);
       
      // This code is contributed by rdtank.

Output

Time Complexit y: O(N) 

Auxiliar y Space : O(1) 

Approach 4 (Using Cyclic Sor t): The idea behind it is as

follows:

All the given array numbers are sor ted and in the

range of 1 to n-1. If the range is 1 to N  then the index

of ever y array element will be the same as (value –

1). Skip to content


Start Your Coding Journey Now! Login Register
Sign in to GeeksforGeeks with Google
Follow the below steps to implement the idea:

Use cyclic sor t to sor t the element s in linear time.


Madhusudhan
pmadhusudhanit@gmail.com
Now traverse from i = 0 to the end of the array:

If arr[i] is not the same as i+1 then the missing


Madhu Sudhan
pasupulatimadhu96@gmail.com
element is (i+1).

If all element s are present then N is the missing element 1 more account

in the range [1, N].

Below is the implementation of the above approach.

C++

// C++ program to find the missing Number


 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the missing number
int getMissingNo(int a[], int n)
{
    int i = 0;
    while (i < n) {
        int correct = a[i] - 1;
        if (a[i] < n && a[i] != a[correct]) {
            swap(a[i], a[correct]);
        }
        else {
            i++;
        }
    }
 
    for (int i = 0; i < n; i++) {
        if (i != a[i] - 1) {
            return i + 1;
        }
    }
 
    return n;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
   
    // Function call
    int miss = getMissingNo(arr, N);
    cout << (miss);
    return 0;
}

Java

// java program to check missingNo


import java.util.*;
public class MissingNumber {
Skip to content
 
Start Your Coding Journey
    // Driver code Now! Login
    public static void main(String[] args)
Register
Sign in to GeeksforGeeks with Google
    {
        int[] arr = { 1, 2, 3, 5 };
        int N = arr.length; Madhusudhan
  pmadhusudhanit@gmail.com

        // Function call


        int ans = getMissingNo(arr, N); Madhu Sudhan
        System.out.println(ans); pasupulatimadhu96@gmail.com
    }
  1 more account
    // Function to find the missing number
    static int getMissingNo(int[] arr, int n)
    {
        int i = 0;
        while (i < n) {
            // as array is of 1 based indexing
            // correct position or index numbe
            // element is element-1 i.e. 1 wil
            // index similarly 2 correct index
            // on...
            int correctpos = arr[i] - 1;
            if (arr[i] < n && arr[i] != arr[co
                // if array element should be
                // size and array element shou
                // its correct position then o
                // its correct position or ind
                swap(arr, i, correctpos);
            }
            else {
                // if element is at its correc
                // just increment i and check
                // array elements
                i++;
            }
        }
        // check for missing element by compar
        // with their index values
        for (int index = 0; index < arr.length
            if (arr[index] != index + 1) {
                return index + 1;
            }
        }
        return arr.length;
    }
 
    static void swap(int[] arr, int i, int cor
    {
        // swap elements with their correct in
        int temp = arr[i];
        arr[i] = arr[correctpos];
        arr[correctpos] = temp;
    }
}
// this code is contributed by devendra solunk

P ython3

# Python3 program to check missingNo


 
# Function to find the missing number
def getMissingNo(arr, n) :
    i = 0;
     
    while (i < n)Skip
: to content
        # as array is of 1 based indexing so t
Start Your Coding
        #Journey Now! or index
correct position Loginnumber of
        # element is element-1 i.e. 1 will
Sign inbe
Register
to GeeksforGeeks with Google
        # index similarly 2 correct index will
        # on...
        correctpos = arr[i] - 1; Madhusudhan
pmadhusudhanit@gmail.com
        if (arr[i] < n and arr[i] != arr[corre
            # if array element should be lesse
Madhu
            # size and array element should noSudhan
            # its correct position then pasupulatimadhu96@gmail.com
only s
            # its correct position or index va
            arr[i],arr[correctpos] = arr[corre 1 more account
 
        else :
            # if element is at its correct pos
            # just increment i and check for r
            # array elements
            i += 1;
             
    # check for missing element by comparing e
    for index in range(n) :
        if (arr[index] != index + 1) :
            return index + 1;
             
    return n;
 
# Driver code
if __name__ == "__main__" :
    arr = [ 1, 2, 3, 5 ];
    N = len(arr);
    print(getMissingNo(arr, N));
 
 
    # This Code is Contributed by AnkThon

C#

// C# program to implement
// the above approach
using System;
class GFG {
 
    // Function to find the missing number
    static int getMissingNo(int[] arr, int n)
    {
        int i = 0;
        while (i < n) {
            // as array is of 1 based indexing
            // correct position or index numbe
            // element is element-1 i.e. 1 wil
            // index similarly 2 correct index
            // on...
            int correctpos = arr[i] - 1;
            if (arr[i] < n && arr[i] != arr[co
                // if array element should be
                // size and array element shou
                // its correct position then o
                // its correct position or ind
                swap(arr, i, correctpos);
            }
            else {
                // if element is at its correc
                // just increment i and check
                // array elements
                i++;
            } Skip to content
        }
Start Your Coding Journey
        // Now!
check for Login by compar Register
missing element
        // with their index values Sign in to GeeksforGeeks with Google
        for (int index = 0; index < n; index++
            if (arr[index] != index + 1) {
                return index + 1; Madhusudhan
            } pmadhusudhanit@gmail.com
        }
        return n; Madhu Sudhan
    } pasupulatimadhu96@gmail.com
 
    static void swap(int[] arr, int i, int cor 1 more account
    {
        // swap elements with their correct in
        int temp = arr[i];
        arr[i] = arr[correctpos];
        arr[correctpos] = temp;
    }
   
    // Driver code
    public static void Main()
    {
        int[] arr = { 1, 2, 4, 5, 6 };
        int N = arr.Length;
       
        // Function call
        int ans = getMissingNo(arr, N);
        Console.Write(ans);
    }
}
 
// This code is contributed by devendra solunk

Javascript

        var arr = [ 1, 2, 3, 5 ];
        var N = arr.length;
        var ans = getMissingNo(arr, N);
        console.log(ans);
 
   // Function to find the missing number
   function getMissingNo(arr, n)
    {
        var i = 0;
        while (i < n) {
            // as array is of 1 based indexing
            // correct position or index numbe
            // element is element-1 i.e. 1 wil
            // index similarly 2 correct index
            // on...
            var correctpos = arr[i] - 1;
            if (arr[i] < n && arr[i] != arr[co
                // if array element should be
                // size and array element shou
                // its correct position then o
                // its correct position or ind
                swap(arr, i, correctpos);
            }
            else {
                // if element is at its correc
                // just increment i and check
                // array elements
                i++;
            }
        }
      // check for missing
Skip element by comparin
to content
        for (var index = 0; index < arr.length
Start Your Coding Journey
            if Now! != index
(arr[index] Login+
                return index + 1;
1) { Register
Sign in to GeeksforGeeks with Google
            }
        }
        return n; Madhusudhan
    } pmadhusudhanit@gmail.com

 
    function swap(arr, i, correctpos) Madhu Sudhan
    { pasupulatimadhu96@gmail.com
      // swap elements with their correct inde
        var temp = arr[i]; 1 more account
        arr[i] = arr[correctpos];
        arr[correctpos] = temp;
    }

Output

Time Complexit y: O(N), requires (N-1) comparisons

Auxiliar y Complexit y: O(1) 

Approach 5 (Use elements as Index and mark the visited

places as negative): Use the below idea to get the approach

Traverse the array. While traversing, use the absolute

value of ever y element as an index and make the

value at this index as negative to mark it visited. To

find missing, traverse the array again and look for a

positive value.

Follow the steps to solve the problem:

Traverse the given array

If the absolute value of current element is greater

than size of the array, then continue.

else multiply the (absolute value of (current element)

– 1)th index with -1.

Initialize a variable ans = size + 1.

Traverse the array and follow the steps:

if the value is positive assign ans = index + 1

Print ans as the missing value.

Below is the implementation of the above approach:

C++

// C++ program to Find the missing element


 
#include <bits/stdc++.h>
using namespace std;
Skip to content
 
Start Your Coding Journey Now!
void findMissing(int
{
arr[], Login
int size) Register
Sign in to GeeksforGeeks with Google
    int i;
   
    for (i = 0; i < size; i++) { Madhusudhan
        if(abs(arr[i]) - 1 == size){ pmadhusudhanit@gmail.com
          continue;
        } Madhu Sudhan
        int ind = abs(arr[i]) - 1; pasupulatimadhu96@gmail.com
        arr[ind] *= -1;
    } 1 more account
 
 
    int ans = size + 1;
    for (i = 0; i < size; i++) {
        if (arr[i] > 0)
            ans = i  + 1;
    }
    cout << ans;
}
 
/* Driver code */
int main()
{
    int arr[] = { 1, 3, 7, 5, 6, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    findMissing(arr, n);
}

Java

// Java code to implement the approach


import java.io.*;
import java.util.*;
 
class GFG {
 
  // Function to find the missing number
  public static void findMissing(int arr[], in
  {
    int i;
 
    for (i = 0; i < size; i++) {
      if (Math.abs(arr[i]) - 1 == size) {
        continue;
      }
      int ind = Math.abs(arr[i]) - 1;
      arr[ind] *= -1;
    }
 
    int ans = size + 1;
    for (i = 0; i < size; i++) {
      if (arr[i] > 0)
        ans = i + 1;
    }
    System.out.println(ans);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = { 1, 3, 7, 5, 6, 2 };
    int n = arr.length;
 
    // Function call
Skip to content
    findMissing(arr, n);
Start Your Coding
  }
}
Journey Now! Login Register
Sign in to GeeksforGeeks with Google
 
// This code is contributed by aarohirai2616.
Madhusudhan
pmadhusudhanit@gmail.com

P ython3 Madhu Sudhan


pasupulatimadhu96@gmail.com

# Function to get the missing number


def findMissing(a, size): 1 more account
 
    for i in range(0, n):
        if (abs(arr[i]) - 1 == size):
            continue
 
        ind = abs(arr[i]) - 1
        arr[ind] *= -1
 
    ans = size + 1
    for i in range(0, n):
        if (arr[i] > 0):
            ans = i + 1
 
    print(ans)
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 3, 7, 5, 6, 2]
    n = len(arr)
 
    # Function call
    findMissing(arr, n)
 
    # This code is contributed by aarohirai261

C#

using System;
public class GFG {
 
  // Function to find the missing number
  public static void findMissing(int[] arr, in
  {
    for (int i = 0; i < size; i++) {
      if (Math.Abs(arr[i]) - 1 == size)
        continue;
 
      int ind = Math.Abs(arr[i]) - 1;
      arr[ind] *= -1;
    }
 
    int ans = size + 1;
    for (int i = 0; i < size; i++) {
      if (arr[i] > 0)
        ans = i + 1;
    }
    Console.WriteLine(ans);
  }
  static public void Main()
  {
    int[] arr = { 1, 3, 7, 5, 6, 2 };
    int n = arr.Length;
 
Skip to content
    // Function call
    findMissing(arr, n);
Start Your Coding
  }
}
Journey Now! Login Register
Sign in to GeeksforGeeks with Google
 
// This code is contributed by nikhilm2302
Madhusudhan
pmadhusudhanit@gmail.com

Javascript Madhu Sudhan


pasupulatimadhu96@gmail.com

// Javascript code to implement the approach


  1 more account
// Function to find the missing number
function findMissing(arr,size){
  let i;
  for (i = 0; i < size; i++) {
            if (Math.abs(arr[i]) - 1 == size)
                continue;
            }
            let ind = Math.abs(arr[i]) - 1;
            arr[ind] *= -1;
        }
 
        let ans = size + 1;
        for (i = 0; i < size; i++) {
            if (arr[i] > 0)
                ans = i + 1;
        }
   
        console.log(ans);
}
 
// Driver code
        let arr = [ 1, 3, 7, 5, 6, 2 ];
        let n = arr.length;
 
        // Function call
       findMissing(arr,n);
 
// This code is contributed by aarohirai2616.

Output

Time Complexit y: O(N) 

Auxiliar y Space : O(1) 

Like 347

Skip to content
Start Your Coding Journey Now!
Previous Next
Login Register
Count the number of Search an element in Sign in to GeeksforGeeks with Google

possible triangles a sorted and rotated


Madhusudhan
Array
pmadhusudhanit@gmail.com

Madhu Sudhan
pasupulatimadhu96@gmail.com

1 more account
Related Articles
1. Find the missing and repeating number

2. Find the smallest missing number

3. Find the missing number in Arithmetic Progression

4. Find the missing number in Geometric Progression

5. Find missing number in another array which is


shuffled copy

6. Find the missing number in a sorted array of limited


range

7. Find the one missing number in range

8. Find the smallest positive number missing from an


unsorted array | Set 2

9. Find the only missing number in a sorted array

10. Find the Missing Number in a sorted array

Ar ticle Contributed By :

GeeksforGeeks

Vote for difficulty

Current difficulty :
Easy

Easy Normal Medium Hard Expert

Improved By : jit_t, YatinGupta, SoumikMondal,


Ankur Goel, mohit kumar 29,
andrew1234,
Vivekkumar Singh,
avsadityavardhan, ukasp, sujitmeshram,
Skip to content
virusbuddha, subhammahato348,
Start Your Coding Journey Now!
surbhityagi15, LoginRajput-Ji,
mayanktyagi1709, Register
Sign in to GeeksforGeeks with Google
rdtank, nijpadariya, palakdwivedi1, mridtz,
akshaysingh98088, pranjalkakkar2181,
adityakumar129, devendrasalunke, Madhusudhan
pmadhusudhanit@gmail.com
lucidcoder121, ankthon, simmytarika5,
rkbhola5, prasanna1995, sagartomar9927,
Madhu Sudhan
animeshdey, harendrakumar123, pasupulatimadhu96@gmail.com

mitalibhola94, manjulgfg, sweetyty,


aarohirai2616, nikhilm2302, sayanc170 1 more account

Article Tags : Accolite, Amazon, Bitwise-XOR, Cisco,


limited-range-elements, Microsoft,
Morgan Stanley, Ola Cabs, Payu,
Qualcomm, Samsung, Visa, Arrays,
Searching
Practice Tags : Accolite, Amazon, Cisco, Microsoft,
Morgan Stanley, Ola Cabs, Payu,
Qualcomm, Samsung, Visa, Arrays,
Searching

Improve Article Report Issue

Company Learn News Languages Web Contribute


About Us DSA
Top News
Python Development Write an
A-143, 9th Floor, Sovereign
Corporate Tower,
Technology Web Tutorials Article
Sector-136, Noida, Uttar Pradesh Careers Algorithms Java
- 201305 Work & Improve an
In Media Data CPP Django Tutorial
feedback@geeksforgeeks.org Career Article
Contact Us Structures Golang HTML
Business Pick Topics to
Privacy SDE Cheat C# JavaScript
Sheet Finance Write
Policy SQL Bootstrap
Machine Lifestyle Write
Copyright Kotlin ReactJS
learning Knowledge Interview
Policy
NodeJS Experience
Advertise CS
Subjects Internships
with us
Video Video
Tutorials Internship
Courses

@geeksforgeeks
, Some rights reserved

You might also like