Open In App

Find the Missing Number

Last Updated : 13 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N-1 with integers in the range of [1, N], the task is to find the missing number from the first N integers.

Note: There are no duplicates in the list.

Examples: 

Input: arr[] = {1, 2, 4, 6, 3, 7, 8}
Output: 5
Explanation: Here the size of the array is 7, so the range will be [1, 7]. The missing number between 1 to 7 is 5

Input: arr[] = {1, 2, 3, 5}, N = 5
Output: 4
Explanation: Here the size of the array is 4, so the range will be [1, 5]. The missing number between 1 to 5 is 4

Recommended Practice

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 elements 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 = 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);
}

C

#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 N)
    {
        int i;
        int temp[] = new int[N + 1];
        for (i = 0; i <= N; i++) {
            temp[i] = 0;
        }

        for (i = 0; i < N; i++) {
            temp[arr[i] - 1] = 1;
        }

        int ans = 0;
        for (i = 0; i <= N; i++) {
            if (temp[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
        findMissing(arr, n);
    }
}

C#

using System;
public class GFG {

  public static void findMissing(int[] arr, int N)
  {
    
    // this will create a new array containing 0
    int[] temp = new int[N + 1];

    for (int i = 0; i < N-1; i++) {
      temp[arr[i] - 1] = 1;
    }

    int ans = 0;
    for (int i = 0; i <= N; i++) {
      if (temp[i] == 0)
        ans = i + 1;
    }
    Console.WriteLine(ans);
  }
  static public void Main()
  {
    int[] arr = { 1, 3, 7, 5, 6, 2 };
    int n = arr.Length;

    findMissing(arr, n);
  }
}

// This code is contributed by nikhilm2302.

Javascript

<script>
// 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);


</script>

Python3

# 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


Output
4




Time Complexity: O(N)
Auxiliary 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.

Find the sum of the numbers in the range [1, N] using the formula N * (N+1)/2. Now find the sum of all the elements in the array and subtract it from the sum of the first N natural numbers. This will give the value of the missing element.

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 start to end.
    • Find the sum of all the array elements.
  • Print the missing number as SumTotal – sum of array

Below is the implementation of the above approach:

C

#include <stdio.h>

// Function to find the missing number
int getMissingNo(int a[], int n)
{
    int i, total;
    total = (n + 1) * (n + 2) / 2;
    for (i = 0; i < n; i++)
        total -= a[i];
    return total;
}

// Driver code
void main()
{
    int arr[] = { 1, 2, 3, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);

    // Function call
    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 n)
    {
       int sum = 0;
        for(int i=0;i<n;i++){
            sum = sum + nums[i];
        }
        return ((n * (n+1))/2 - 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));
    }
}

Python

# 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

C#

// C# program to find missing Number
using System;

class GFG {
    // Function to find missing number
    static int getMissingNo(int[] a, int n)
    {
        int total = (n + 1) * (n + 2) / 2;

        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_

Javascript

<script>
 
    // Function to get the missing number
    function getMissingNo(a, n) {
 
        let total = Math.floor((n + 1) * (n + 2) / 2);
        for (let i = 0; i < n; i++)
            total -= a[i];
        return total;
    }
 
    // Driver Code

    let arr = [ 1, 2, 3, 5 ];
    let N = arr.length;
    let miss = getMissingNo(arr, N);
    document.write(miss);

// This code is contributed by Surbhi Tyagi 

</script>

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.
?>

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;
}


Output
4




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

Modification for Overflow: The approach remains the same but there can be an overflow if N is large. 

In order 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). This way there won’t be any integer overflow.

Algorithm: 

  • Create a variable total = 1 which will store the total sum of first n elements.
  • Traverse the array from start to end.
    • Update the value of total as total += i , now decrease value of total by current array element.
  • Print the missing number , which will be present in the total variable.

Below is the implementation of the above approach:

C

#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 (adityakumar129)

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 };
        int N = arr.length;
      
        // Function call
        System.out.println(getMissingNo(arr, N));
    }
}

// This code is contributed by Aditya Kumar (adityakumar129)

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

<script>

// a represents the array
// n : Number of elements in array a
function getMissingNo(a, n) 
{ 
    let i, total=1; 
    
    for (i = 2; i< (n+1); i++)
    {
        total += i;
        total -= a[i-2];
    }
    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

</script>

C++14

#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 -= a[i - 2];
    }
    return total;
}

// Driver Program
int main()
{
    int arr[] = { 1, 2, 3, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Function call
    cout << getMissingNo(arr, N);
    return 0;
}

// This code is contributed by Aditya Kumar (adityakumar129)

Python3

# 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


Output
4




Time Complexity: O(N).  Only one traversal of the array is needed.
Auxiliary Space: O(1). No extra space is needed

Approach 3 (Using binary operations): This method uses the technique of XOR to solve the problem.  

XOR has certain properties 

  • Assume a1 ⊕ a2 ⊕ a3 ⊕ . . . ⊕ an = a and a1 ⊕ a2 ⊕ a3 ⊕ . . . ⊕ an-1 = b
  • Then a ⊕ b = an

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 every index, update a as a = a ^ i
  • Now traverse the array from i = start to end.
    • For every index, update b as b = b ^ arr[i].
  • The missing number is a ^ b.

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>
using namespace std;

// Function to get the missing number
int getMissingNo(int a[], int n)
{
    // For xor of all the elements in array
    int x1 = a[0];

    // For xor of all the elements from 1 to n+1
    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;
}

C

#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+1
    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]);

    // Function call
    int miss = getMissingNo(arr, N);
    printf("%d", miss);
}

Java

// Java program to find missing Number
// using xor

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 array
        for (int i = 1; i < n; i++)
            x1 = x1 ^ a[i];

        // For xor of all the elements from 1 to n+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);
    }
}

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 array
        for (int i = 1; i < n; i++)
            x1 = x1 ^ a[i];

        // For xor of all the elements from 1 to n+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_

Javascript

<script>
      // Function to get the missing number
      function getMissingNo(a, n)
      {
      
        // For xor of all the elements in array
        var x1 = a[0];

        // For xor of all the elements from 1 to n+1
        var x2 = 1;
        for (var i = 1; i < n; i++) x1 = x1 ^ a[i];
        for (var i = 2; i <= n + 1; i++) x2 = x2 ^ i;

        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.
    </script>

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; 
    
    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
$arr = array(1, 2, 3, 5);
$N = 4;
$miss = getMissingNo($arr, $N);
echo($miss);

// This code is contributed by Ajit.
?>

Python3

# 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
if __name__ == '__main__':

    arr = [1, 2, 3, 5]
    N = len(arr)

    # Driver code
    miss = getMissingNo(arr, N)
    print(miss)

# This code is contributed by Yatin Gupta


Output
4




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

Approach 4 (Using Cyclic Sort): The idea behind it is as follows:

All the given array numbers are sorted and in the range of 1 to n-1. If the range is 1 to N  then the index of every array element will be the same as (value – 1).

Follow the below steps to implement the idea:

  • Use cyclic sort to sort the elements in linear time.
  • Now traverse from i = 0 to the end of the array:
    • If arr[i] is not the same as i+1 then the missing element is (i+1).
  • If all elements are present then N is the missing element 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;
}

C

// C program to find the missing Number

#include <stdio.h>

// 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]) {
            int temp = a[i];
            a[i] = a[correct];
            a[correct] = temp;
        }
        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);
    printf("%d", miss);
    return 0;
}

Java

// java program to check missingNo
import java.util.*;
public class MissingNumber {

    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 5 };
        int N = arr.length;

        // Function call
        int ans = getMissingNo(arr, N);
        System.out.println(ans);
    }

    // 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 so the
            // correct position or index number of each
            // element is element-1 i.e. 1 will be at 0th
            // index similarly 2 correct index will 1 so
            // on...
            int correctpos = arr[i] - 1;
            if (arr[i] < n && arr[i] != arr[correctpos]) {
                // if array element should be lesser than
                // size and array element should not be at
                // its correct position then only swap with
                // its correct position or index value
                swap(arr, i, correctpos);
            }
            else {
                // if element is at its correct position
                // just increment i and check for remaining
                // array elements
                i++;
            }
        }
        // check for missing element by comparing elements
        // with their index values
        for (int index = 0; index < arr.length; index++) {
            if (arr[index] != index + 1) {
                return index + 1;
            }
        }
        return arr.length;
    }

    static void swap(int[] arr, int i, int correctpos)
    {
        // swap elements with their correct indexes
        int temp = arr[i];
        arr[i] = arr[correctpos];
        arr[correctpos] = temp;
    }
}
// this code is contributed by devendra solunke

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 so the
            // correct position or index number of each
            // element is element-1 i.e. 1 will be at 0th
            // index similarly 2 correct index will 1 so
            // on...
            int correctpos = arr[i] - 1;
            if (arr[i] < n && arr[i] != arr[correctpos]) {
                // if array element should be lesser than
                // size and array element should not be at
                // its correct position then only swap with
                // its correct position or index value
                swap(arr, i, correctpos);
            }
            else {
                // if element is at its correct position
                // just increment i and check for remaining
                // array elements
                i++;
            }
        }
        // check for missing element by comparing elements
        // with their index values
        for (int index = 0; index < n; index++) {
            if (arr[index] != index + 1) {
                return index + 1;
            }
        }
        return n;
    }

    static void swap(int[] arr, int i, int correctpos)
    {
        // swap elements with their correct indexes
        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 solunke

Javascript

// javascript program to check missingNo
<script>
        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 so the
            // correct position or index number of each
            // element is element-1 i.e. 1 will be at 0th
            // index similarly 2 correct index will 1 so
            // on...
            var correctpos = arr[i] - 1;
            if (arr[i] < n && arr[i] != arr[correctpos]) {
                // if array element should be lesser than
                // size and array element should not be at
                // its correct position then only swap with
                // its correct position or index value
                swap(arr, i, correctpos);
            }
            else {
                // if element is at its correct position
                // just increment i and check for remaining
                // array elements
                i++;
            }
        }
      // check for missing element by comparing elements with their index values 
        for (var index = 0; index < arr.length; index++) {
            if (arr[index] != index + 1) {
                return index + 1;
            }
        }
        return n;
    }

    function swap(arr, i, correctpos)
    {
      // swap elements with their correct indexes
        var temp = arr[i];
        arr[i] = arr[correctpos];
        arr[correctpos] = temp;
    }
</script>
// this code is contributed by devendra solunke

Python3

# Python3 program to check missingNo

# Function to find the missing number
def getMissingNo(arr, n) :
    i = 0;
    
    while (i < n) :
        # as array is of 1 based indexing so the
        # correct position or index number of each
        # element is element-1 i.e. 1 will be at 0th
        # index similarly 2 correct index will 1 so
        # on...
        correctpos = arr[i] - 1;
        if (arr[i] < n and arr[i] != arr[correctpos]) :
            # if array element should be lesser than
            # size and array element should not be at
            # its correct position then only swap with
            # its correct position or index value
            arr[i],arr[correctpos] = arr[correctpos], arr[i]

        else :
            # if element is at its correct position
            # just increment i and check for remaining
            # array elements
            i += 1;
            
    # check for missing element by comparing elements with their index values 
    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


Output
4




Time Complexity: O(N), requires (N-1) comparisons
Auxiliary Complexity: 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 every 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;

void findMissing(int arr[], int size)
{
    int i;
  
    for (i = 0; i < size; i++) {
        if(abs(arr[i]) - 1 == size){
          continue;
        }
        int ind = abs(arr[i]) - 1;
        arr[ind] *= -1;
    }


    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);
}

C

// C program to Find the missing element

#include <stdio.h>
#include <stdlib.h>

void findMissing(int arr[], int size)
{
    int i;

    for (i = 0; i < size; i++) {
        if (abs(arr[i]) - 1 == size) {
            continue;
        }
        int ind = abs(arr[i]) - 1;
        arr[ind] *= -1;
    }

    int ans = size + 1;
    for (i = 0; i < size; i++) {
        if (arr[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);
    return 0;
}

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 size)
  {
    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
    findMissing(arr, n);
  }
}

// This code is contributed by aarohirai2616.

C#

using System;
public class GFG {

  // Function to find the missing number
  public static void findMissing(int[] arr, int size)
  {
    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;

    // Function call
    findMissing(arr, n);
  }
}

// This code is contributed by nikhilm2302

Javascript

<script>
// Javascript code to implement the approach

// 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.
</script>

Python3

# Function to get the missing number
def findMissing(a, size):

    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 aarohirai2616.


Output
4




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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads