Find the repeating and the missing | Added 3 new methods

Given an unsorted array of size n. Array elements are in the range from 1 to n. One number from set {1, 2, …n} is missing and one number occurs twice in the array. Find these two numbers.

Examples:

Input: arr[] = {3, 1, 3}
Output: Missing = 2, Repeating = 3
Explanation: In the array,
2 is missing and 3 occurs twice

Input: arr[] = {4, 3, 6, 2, 1, 1}
Output: Missing = 5, Repeating = 1

Below are various methods to solve the problems:

• Method 1 (Use Sorting)

Approach:

1. Sort the input array.
2. Traverse the array and check for missing and repeating.

Time Complexity: O(nLogn)

Thanks to LoneShadow for suggesting this method.

• Method 2 (Use count array)

Approach:

1. Create a temp array temp[] of size n with all initial values as 0.
2. Traverse the input array arr[], and do following for each arr[i]
• if(temp[arr[i]] == 0) temp[arr[i]] = 1;
• if(temp[arr[i]] == 1) output “arr[i]” //repeating
3. Traverse temp[] and output the array element having value as 0 (This is the missing element)

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

• Method 3 (Use elements as Index and mark the visited places)

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. If something is already marked negative then this is the repeating element. To find missing, traverse the array again and look for a positive value.

C++

 // C++ program to Find the repeating // and missing elements    #include using namespace std;    void printTwoElements(int arr[], int size) {     int i;     cout << " The repeating element is ";        for (i = 0; i < size; i++) {         if (arr[abs(arr[i]) - 1] > 0)             arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];         else             cout << abs(arr[i]) << " ";     }        cout << "and the missing element is ";     for (i = 0; i < size; i++) {         if (arr[i] > 0)             cout << (i + 1);     } }    /* Driver code */ int main() {     int arr[] = { 7, 3, 4, 5, 5, 6, 2 };     int n = sizeof(arr) / sizeof(arr);     printTwoElements(arr, n); }    // This code is contributed by Shivi_Aggarwal

C

 // C program to Find the repeating // and missing elements    #include #include    void printTwoElements(int arr[], int size) {     int i;     printf(" The repeating element is");        for (i = 0; i < size; i++) {         if (arr[abs(arr[i]) - 1] > 0)             arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];         else             printf(" %d ", abs(arr[i]));     }        printf(" and the missing element is ");     for (i = 0; i < size; i++) {         if (arr[i] > 0)             printf("%d", i + 1);     } }    // Driver code int main() {     int arr[] = { 7, 3, 4, 5, 5, 6, 2 };     int n = sizeof(arr) / sizeof(arr);     printTwoElements(arr, n);     return 0; }

Java

 // Java program to Find the repeating // and missing elements    import java.io.*;    class GFG {        static void printTwoElements(int arr[], int size)     {         int i;         System.out.print("The repeating element is ");            for (i = 0; i < size; i++) {             int abs_val = Math.abs(arr[i]);             if (arr[abs_val - 1] > 0)                 arr[abs_val - 1] = -arr[abs_val - 1];             else                 System.out.println(abs_val);         }            System.out.print("And the missing element is ");         for (i = 0; i < size; i++) {             if (arr[i] > 0)                 System.out.println(i + 1);         }     }        // Driver code     public static void main(String[] args)     {         int arr[] = { 7, 3, 4, 5, 5, 6, 2 };         int n = arr.length;         printTwoElements(arr, n);     } }    // This code is contributed by Gitanjali

Python3

 # Python3 code to Find the repeating  # and the missing elements    def printTwoElements( arr, size):     for i in range(size):         if arr[abs(arr[i])-1] > 0:             arr[abs(arr[i])-1] = -arr[abs(arr[i])-1]         else:             print("The repeating element is", abs(arr[i]))                    for i in range(size):         if arr[i]>0:             print("and the missing element is", i + 1)    # Driver program to test above function */ arr = [7, 3, 4, 5, 5, 6, 2] n = len(arr) printTwoElements(arr, n)    # This code is contributed by "Abhishek Sharma 44"

C#

 // C# progam to Find the repeating // and missing elements    using System;    class GFG {     static void printTwoElements(int[] arr, int size)     {         int i;         Console.Write("The repeating element is ");            for (i = 0; i < size; i++) {             int abs_val = Math.Abs(arr[i]);             if (arr[abs_val - 1] > 0)                 arr[abs_val - 1] = -arr[abs_val - 1];             else                 Console.WriteLine(abs_val);         }            Console.Write("And the missing element is ");         for (i = 0; i < size; i++) {             if (arr[i] > 0)                 Console.WriteLine(i + 1);         }     }        // Driver program     public static void Main()     {         int[] arr = { 7, 3, 4, 5, 5, 6, 2 };         int n = arr.Length;         printTwoElements(arr, n);     } } // This code is contributed by Sam007

PHP

 0)             \$arr[abs(\$arr[\$i]) - 1] =              - \$arr[abs(\$arr[\$i]) - 1];         else             echo ( abs(\$arr[\$i]));     }        echo " and the missing element is ";     for(\$i = 0; \$i < \$size; \$i++)     {         if(\$arr[\$i] > 0)             echo(\$i + 1);     } }            // Driver Code     \$arr = array(7, 3, 4, 5, 5, 6, 2);     \$n = count(\$arr);     printTwoElements(\$arr, \$n);    // This code is contributed by anuj_67. ?>

Output:

The repeating element is 5
and the missing element is 1

Time Complexity: O(n)

Thanks to Manish Mishra for suggesting this method.

• Method 4 (Make two equations)

Approach:

1. Let x be the missing and y be the repeating element.
2. Get the the sum of all numbers using formula S = n(n+1)/2 – x + y
3. Get product of all numbers using formula P = 1*2*3*…*n * y / x
4. The above two steps give us two equations, we can solve the equations and get the values of x and y.

Time Complexity: O(n)

Thanks to disappearedng for suggesting this solution.

Note: This method can cause arithmetic overflow as we calculate product and sum of all array elements.

• Method 5 (Use XOR)

Approach:

1. Let x and y be the desired output elements.
2. Calculate XOR of all the array elements.

xor1 = arr^arr^arr…..arr[n-1]

3. XOR the result with all numbers from 1 to n

xor1 = xor1^1^2^…..^n

4. In the result xor1, all elements would nullify each other except x and y. All the bits that are set in xor1 will be set in either x or y. So if we take any set bit (We have chosen the rightmost set bit in code) of xor1 and divide the elements of the array in two sets – one set of elements with same bit set and other set with same bit not set. By doing so, we will get x in one set and y in another set. Now if we do XOR of all the elements in first set, we will get x, and by doing same in other set we will get y..

Below is the implementation of the above approach:

C++

 // C++ program to Find the repeating // and missing elements    #include using namespace std;    /* The output of this function is stored at *x and *y */ void getTwoElements(int arr[], int n,                     int* x, int* y) {     /* Will hold xor of all elements      and numbers from 1 to n */     int xor1;        /* Will have only single set bit of xor1 */     int set_bit_no;        int i;     *x = 0;     *y = 0;        xor1 = arr;        /* Get the xor of all array elements */     for (i = 1; i < n; i++)         xor1 = xor1 ^ arr[i];        /* XOR the previous result with numbers      from 1 to n*/     for (i = 1; i <= n; i++)         xor1 = xor1 ^ i;        /* Get the rightmost set bit in set_bit_no */     set_bit_no = xor1 & ~(xor1 - 1);        /* Now divide elements into two      sets by comparing a rightmost set     bit of xor1 with the bit at the same      position in each element. Also,      get XORs of two sets. The two     XORs are the output elements.      The following two for loops      serve the purpose */     for (i = 0; i < n; i++) {         if (arr[i] & set_bit_no)             /* arr[i] belongs to first set */             *x = *x ^ arr[i];            else             /* arr[i] belongs to second set*/             *y = *y ^ arr[i];     }     for (i = 1; i <= n; i++) {         if (i & set_bit_no)             /* i belongs to first set */             *x = *x ^ i;            else             /* i belongs to second set*/             *y = *y ^ i;     }        /* *x and *y hold the desired         output elements */ }    /* Driver code */ int main() {     int arr[] = { 1, 3, 4, 5, 5, 6, 2 };     int* x = (int*)malloc(sizeof(int));     int* y = (int*)malloc(sizeof(int));     int n = sizeof(arr) / sizeof(arr);        getTwoElements(arr, n, x, y);     cout << " The missing element is " << *x << " and the repeating"          << " number is " << *y;     getchar(); }    // This code is contributed by Code_Mech

C

 // C program to Find the repeating // and missing elements    #include #include    /* The output of this function is stored at    *x and *y */ void getTwoElements(int arr[], int n, int* x, int* y) {     /* Will hold xor of all elements and numbers         from 1 to n */     int xor1;        /* Will have only single set bit of xor1 */     int set_bit_no;        int i;     *x = 0;     *y = 0;        xor1 = arr;        /* Get the xor of all array elements */     for (i = 1; i < n; i++)         xor1 = xor1 ^ arr[i];        /* XOR the previous result with numbers         from 1 to n*/     for (i = 1; i <= n; i++)         xor1 = xor1 ^ i;        /* Get the rightmost set bit in set_bit_no */     set_bit_no = xor1 & ~(xor1 - 1);        /* Now divide elements in two sets by comparing      rightmost set bit of xor1 with bit at same      position in each element. Also, get XORs of two      sets. The two XORs are the output elements. The     following two for loops serve the purpose */     for (i = 0; i < n; i++) {         if (arr[i] & set_bit_no)             /* arr[i] belongs to first set */             *x = *x ^ arr[i];            else             /* arr[i] belongs to second set*/             *y = *y ^ arr[i];     }     for (i = 1; i <= n; i++) {         if (i & set_bit_no)             /* i belongs to first set */             *x = *x ^ i;            else             /* i belongs to second set*/             *y = *y ^ i;     }        /* *x and *y hold the desired output elements */ }    /* Driver program to test above function */ int main() {     int arr[] = { 1, 3, 4, 5, 5, 6, 2 };     int* x = (int*)malloc(sizeof(int));     int* y = (int*)malloc(sizeof(int));     int n = sizeof(arr) / sizeof(arr);        getTwoElements(arr, n, x, y);     printf(" The missing element is %d"            " and the repeating number"            " is %d",            *x, *y);     getchar(); }

Java

 // Java program to Find the repeating // and missing elements    import java.io.*;    class GFG {     static int x, y;        static void getTwoElements(int arr[], int n)     {         /* Will hold xor of all elements        and numbers from 1 to n  */         int xor1;            /* Will have only single set bit of xor1 */         int set_bit_no;            int i;         x = 0;         y = 0;            xor1 = arr;            /* Get the xor of all array elements  */         for (i = 1; i < n; i++)             xor1 = xor1 ^ arr[i];            /* XOR the previous result with numbers from         1 to n*/         for (i = 1; i <= n; i++)             xor1 = xor1 ^ i;            /* Get the rightmost set bit in set_bit_no */         set_bit_no = xor1 & ~(xor1 - 1);            /* Now divide elements into two sets by comparing     rightmost set bit of xor1 with the bit at the same      position in each element. Also, get XORs of two     sets. The two XORs are the output elements. The      following two for loops serve the purpose */         for (i = 0; i < n; i++) {             if ((arr[i] & set_bit_no) != 0)                 /* arr[i] belongs to first set */                 x = x ^ arr[i];                else                 /* arr[i] belongs to second set*/                 y = y ^ arr[i];         }         for (i = 1; i <= n; i++) {             if ((i & set_bit_no) != 0)                 /* i belongs to first set */                 x = x ^ i;                else                 /* i belongs to second set*/                 y = y ^ i;         }            /* *x and *y hold the desired output elements */     }     /* Driver program to test above function */     public static void main(String[] args)     {         int arr[] = { 1, 3, 4, 5, 1, 6, 2 };            int n = arr.length;         getTwoElements(arr, n);         System.out.println(" The missing element is  "                            + x + "and the "                            + "repeating number is "                            + y);     } }    // This code is contributed by Gitanjali.

C#

 // C# progam to Find the repeating // and missing elements    using System;    class GFG {     static int x, y;        static void getTwoElements(int[] arr, int n)     {         /* Will hold xor of all elements         and numbers from 1 to n */         int xor1;            /* Will have only single set bit of xor1 */         int set_bit_no;            int i;         x = 0;         y = 0;            xor1 = arr;            /* Get the xor of all array elements */         for (i = 1; i < n; i++)             xor1 = xor1 ^ arr[i];            /* XOR the previous result with numbers from          1 to n*/         for (i = 1; i <= n; i++)             xor1 = xor1 ^ i;            /* Get the rightmost set bit in set_bit_no */         set_bit_no = xor1 & ~(xor1 - 1);            /* Now divide elements in two sets by comparing         rightmost set bit of xor1 with bit at same          position in each element. Also, get XORs of two         sets. The two XORs are the output elements.The          following two for loops serve the purpose */         for (i = 0; i < n; i++) {             if ((arr[i] & set_bit_no) != 0)                    /* arr[i] belongs to first set */                 x = x ^ arr[i];                else                    /* arr[i] belongs to second set*/                 y = y ^ arr[i];         }         for (i = 1; i <= n; i++) {             if ((i & set_bit_no) != 0)                    /* i belongs to first set */                 x = x ^ i;                else                    /* i belongs to second set*/                 y = y ^ i;         }            /* *x and *y hold the desired output elements */     }        // Driver program     public static void Main()     {         int[] arr = { 1, 3, 4, 5, 1, 6, 2 };            int n = arr.Length;         getTwoElements(arr, n);         Console.Write(" The missing element is "                       + x + "and the "                       + "repeating number is "                       + y);     } }    // This code is contributed by Sam007

PHP



Output:

The missing element is 7 and the repeating number is 5

Time Complexity: O(n)

This method doesn’t cause overflow, but it doesn’t tell which one occurs twice and which one is missing. We can add one more step that checks which one is missing and which one is repeating. This can be easily done in O(n) time.

• Method 6 (Use a Map)

Approach:
This method involves creating a Hashtable with the help of Map. In this, the elements are mapped to their natural index. In this process, if an element is mapped twice, then it is the repeating element. And if an element’s mapping is not there, then it is the missing element.

Below is the implementation of the above approach:

 // Java program to find the // repeating and missing elements // using Maps    import java.util.*;    public class Test1 {        public static void main(String[] args)     {            int[] arr = { 4, 3, 6, 2, 1, 1 };            Map numberMap             = new HashMap<>();            int max = arr.length;            for (Integer i : arr) {                if (numberMap.get(i) == null) {                 numberMap.put(i, true);             }             else {                 System.out.println("Repeating = " + i);             }         }         for (int i = 1; i <= max; i++) {             if (numberMap.get(i) == null) {                 System.out.println("Missing = " + i);             }         }     } }

Output:

Repeating = 1
Missing = 5

• Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.