Find missing elements from an Array

19 Jun, 2022
Given a list of integers from the range [1, N] with some of the elements missing. The task is to find the missing elements. Note that there can be duplicates in the list.Examples: 
Input: arr[] = {1, 3, 3, 3, 5}
Output: 2 4

Input: arr[] = {1, 2, 3, 4, 4, 7, 7} 
Output: 5 6
Approach1: In the given range [1, N] there should be an element corresponding to each index. If an element is missing then its index will never be visited.  
Traverse the array:
For each element:
    if array[element] > 0:
          Mark the element as visited
Again, traverse the array:
     if element isNot Visited:
           add it as missing element
Below is the implementation of the above approach:  
C++
C
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the missing elementsvector<int> missing_elements(vector<int> vec){     // Vector to store the list    // of missing elements    vector<int> mis;     // For every given element    for (int i = 0; i < vec.size(); i++) {         // Find its index        int temp = abs(vec[i]) - 1;         // Update the element at the found index        vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp];    }    for (int i = 0; i < vec.size(); i++)         // Current element was not present        // in the original vector        if (vec[i] > 0)            mis.push_back(i + 1);     return mis;} // Driver codeint main(){    vector<int> vec = { 3, 3, 3, 5, 1 };     // Vector to store the returned    // list of missing elements    vector<int> miss_ele = missing_elements(vec);     // Print the list of elements    for (int i = 0; i < miss_ele.size(); i++)        cout << miss_ele[i] << " ";     return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C implementation of the approach#include <stdio.h>#include <stdlib.h> // Function to find the missing elementsvoid missing_elements(int vec[], int n){    int mis[n];    for (int i = 0; i < n; i++)        mis[i] = -1;     // For every given element    for (int i = 0; i < n; i++) {        // Find its index        int temp = abs(vec[i]) - 1;        // Update the element at the found index        vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp];    }    // Current element was not present in the original    // vector    for (int i = 0; i < n; i++)        if (vec[i] > 0)            mis[i] = (i + 1);    int miss_ele_size = sizeof(mis) / sizeof(mis[0]);    for (int i = 0; i < miss_ele_size; i++) {        if (mis[i] != -1)            printf("%d ", mis[i]);    }} // Driver codeint main(){    int vec[] = { 3, 3, 3, 5, 1 };    int vec_size = sizeof(vec) / sizeof(vec[0]);    missing_elements(vec, vec_size);     return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java implementation of the above approachimport java.util.*; class GFG {     // Function to find the missing elements    static Vector missing_elements(Vector vec)    {         // Vector to store the list        // of missing elements        Vector mis = new Vector();         // For every given element        for (int i = 0; i < vec.size(); i++) {             // Find its index            int temp = Math.abs((int)vec.get(i)) - 1;             // Update the element at the found index            if ((int)vec.get(temp) > 0)                vec.set(temp, -(int)vec.get(temp));            else                vec.set(temp, vec.get(temp));        }        for (int i = 0; i < vec.size(); i++) {            // Current element was not present            // in the original vector            if ((int)vec.get(i) > 0)                mis.add(i + 1);        }        return mis;    }     // Driver code    public static void main(String args[])    {        Vector vec = new Vector();        vec.add(3);        vec.add(3);        vec.add(3);        vec.add(5);        vec.add(1);         // Vector to store the returned        // list of missing elements        Vector miss_ele = missing_elements(vec);         // Print the list of elements        for (int i = 0; i < miss_ele.size(); i++)            System.out.print(miss_ele.get(i) + " ");    }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 implementation of the approach # Function to find the missing elementsdef missing_elements(vec):     # Vector to store the list    # of missing elements    mis = []     # For every given element    for i in range(len(vec)):         # Find its index        temp = abs(vec[i]) - 1         # Update the element at the found index        if vec[temp] > 0:            vec[temp] = -vec[temp]     for i in range(len(vec)):         # Current element was not present        # in the original vector        if (vec[i] > 0):            mis.append(i + 1)     return mis # Driver codevec = [3, 3, 3, 5, 1] # Vector to store the returned# list of missing elementsmiss_ele = missing_elements(vec) # Print the list of elementsfor i in range(len(miss_ele)):    print(miss_ele[i], end = " ") # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System;using System.Collections.Generic;             class GFG{         // Function to find the missing elements    static List<int> missing_elements(List<int> vec)    {             // List<int> to store the list        // of missing elements        List<int> mis = new List<int>();             // For every given element        for (int i = 0; i < vec.Count; i++)        {                 // Find its index            int temp = Math.Abs((int)vec[i]) - 1;                 // Update the element at the found index            if ((int)vec[temp] > 0)                vec[temp] = -(int)vec[temp];            else                vec[temp] = vec[temp];        }        for (int i = 0; i < vec.Count; i++)        {            // Current element was not present            // in the original vector            if ((int)vec[i] > 0)                mis.Add(i + 1);        }        return mis;    }         // Driver code    public static void Main(String []args)    {        List<int> vec = new List<int>();        vec.Add(3);        vec.Add(3);        vec.Add(3);        vec.Add(5);        vec.Add(1);                 // List to store the returned        // list of missing elements        List<int> miss_ele = missing_elements(vec);             // Print the list of elements        for (int i = 0; i < miss_ele.Count; i++)            Console.Write(miss_ele[i] + " ");    }} // This code is contributed by 29AjayKumar
<script>     // Javascript implementation of the approach         // Function to find the missing elements    function missing_elements(vec)    {              // Vector to store the list        // of missing elements        let mis = [];              // For every given element        for (let i = 0; i < vec.length; i++) {                  // Find its index            let temp = Math.abs(vec[i]) - 1;                  // Update the element at the found index            vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp];        }        for (let i = 0; i < vec.length; i++)                  // Current element was not present            // in the original vector            if (vec[i] > 0)                mis.push(i + 1);              return mis;    }         let vec = [ 3, 3, 3, 5, 1 ];      // Vector to store the returned    // list of missing elements    let miss_ele = missing_elements(vec);      // Print the list of elements    for (let i = 0; i < miss_ele.length; i++)        document.write(miss_ele[i] + " "); </script>
2 4 
Time Complexity: O(N), where N is the length of the vector vec.
Auxiliary Space: O(N)
More Efficient Approach:
Approach2: In the given range [1, N] there should be an element corresponding to each index. So if it’s in sorted fashion in O(N) time, then those elements that are not there can be easily found.
Algorithm:
Keep an i pointer from 0 to N-1If the element is in the correct position then don’t swap, increment iElse make a swap with the correct position.Correct Position means Element should be in Element -1 index in our caseIt can handle duplicates too.Then make a for loop,IF we find Arr[i] = i+1, then i+1 is present.Else i+1 is missing.
Keep an i pointer from 0 to N-1
If the element is in the correct position then don’t swap, increment i
Else make a swap with the correct position.
Correct Position means Element should be in Element -1 index in our case
It can handle duplicates too.
Then make a for loop,
IF we find Arr[i] = i+1, then i+1 is present.
Else i+1 is missing.
The CRUX is: If an element is missing, someone in the 1 to N range duplicate is occupying that place.
Example Run Through (Manual):
Example on own by R.Balakrishnan from lucidchart tool 
Below is the CODE implementation of the above approach with all test cases:  
C++
// C++ program to Find missing elements from an Array#include <algorithm>#include <iostream>#include <vector>using namespace std; // Complexities// O(N+N) = O(N) time and O(1) Spacevoid FindMissing(vector<int> arr){    int i = 0;    int N = arr.size();    while (i < N) {        int correct = arr[i] - 1; // as 0 based indxing        if (arr[i] != arr[correct]) {            swap(arr[i], arr[correct]);        }        else {            i++;        }    }     for (i = 0; i < N; i++) {        if (arr[i] != i + 1) {            cout << i + 1 << " ";        }    }    cout << "\n";} int main(){     // Diff Test cases    vector<int> nums = { 3, 3, 3, 5, 1 };    FindMissing(nums);    vector<int> nums2 = { 1, 3, 3, 3, 5 };    FindMissing(nums2);    vector<int> nums3 = { 1, 2, 3, 4, 4, 7, 7 };    FindMissing(nums3);} // Code done by R.Balakrishnan (rbkraj000)
2 4 
2 4 
5 6 

Time Complexity: O(N), where N is the length of the input vector.
Even in the worst case, there will be N-1 Swaps + N-1 Comparisons done. So asymptotically it’s O(N).
Auxiliary Space: O(1) 
mohit kumar 29
ankthon
29AjayKumar
subhammahato348
divyesh072019
adityakumar129
rbkraj000
Constructive Algorithms
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.