Thursday, December 26, 2024
Google search engine
HomeData Modelling & AIFind the two repeating elements in a given array

Find the two repeating elements in a given array

Given an array arr[] of N+2 elements. All elements of the array are in the range of 1 to N. And all elements occur once except two numbers which occur twice. Find the two repeating numbers. 

Examples:

Input: arr = [4, 2, 4, 5, 2, 3, 1], N = 5
Output: 4 2
Explanation: The above array has n + 2 = 7 elements with all elements occurring once except 2 and 4 which occur twice. So the output should be 4 2.

Input: arr = [2, 1, 2, 1, 3], N = 3
Output: 1 2
Explanation: The above array has n + 2 = 5 elements with all elements occurring once except 1 and 2 which occur twice. So the output should be 1 2.

Recommended Practice

Naive Approach:

The idea is to use two loops. 

Follow the steps below to solve the problem:

  • In the outer loop, pick elements one by one and count the number of occurrences of the picked element using a nested loop.
  • Whenever an element is found to be equal to the picked element in nested then print that element.

Below is the implementation of the above approach.

C++




// C++ program to Find the two repeating
// elements in a given array
#include <bits/stdc++.h>
using namespace std;
 
void printTwoRepeatNumber(int arr[], int size)
{
    int i, j;
    cout << "Repeating elements are ";
    for (i = 0; i < size; i++) {
        for (j = i + 1; j < size; j++) {
            if (arr[i] == arr[j]) {
                cout << arr[i] << " ";
                break;
            }
        }
    }
}
 
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
   
    printTwoRepeatNumber(arr, arr_size);
    return 0;
}


C




#include <stdio.h>
#include <stdlib.h>
void printRepeating(int arr[], int size)
{
    int i, j;
    printf(" Repeating elements are ");
    for (i = 0; i < size - 1; i++)
        for (j = i + 1; j < size; j++)
            if (arr[i] == arr[j])
                printf("%d ", arr[i]);
}
 
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    getchar();
    return 0;
}


Java




// Java code to implement the approach
 
import java.io.*;
 
class RepeatElement {
    void printRepeating(int arr[], int size)
    {
        int i, j;
        System.out.print("Repeating Elements are ");
        for (i = 0; i < size - 1; i++) {
            for (j = i + 1; j < size; j++) {
                if (arr[i] == arr[j])
                    System.out.print(arr[i] + " ");
            }
        }
    }
 
    public static void main(String[] args)
    {
        RepeatElement repeat = new RepeatElement();
        int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.length;
        repeat.printRepeating(arr, arr_size);
    }
}


Python3




# Python3 program to Find the two
# repeating elements in a given array
 
 
def printRepeating(arr, size):
 
    print("Repeating elements are", end=' ')
    for i in range(0, size-1):
        for j in range(i + 1, size):
            if arr[i] == arr[j]:
                print(arr[i], end=' ')
 
 
# Driver code
arr = [4, 2, 4, 5, 2, 3, 1]
arr_size = len(arr)
printRepeating(arr, arr_size)
 
# This code is contributed by Smitha Dinesh Semwal


C#




using System;
 
class GFG {
 
    static void printRepeating(int[] arr, int size)
    {
        int i, j;
 
        Console.Write("Repeating Elements are ");
        for (i = 0; i < size - 1; i++) {
            for (j = i + 1; j < size; j++) {
                if (arr[i] == arr[j])
                    Console.Write(arr[i] + " ");
            }
        }
    }
    // driver code
    public static void Main()
    {
        int[] arr = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.Length;
 
        printRepeating(arr, arr_size);
    }
}
 
// This code is contributed by Sam007


PHP




<?php
// PHP program to Find the two
// repeating elements in
// a given array
 
function printRepeating($arr, $size)
{
    $i;
    $j;
    echo " Repeating elements are ";
 
    for($i = 0; $i < $size-1; $i++)
        for($j = $i + 1; $j < $size; $j++)
            if($arr[$i] == $arr[$j])
                echo $arr[$i], " ";
}
 
// Driver Code
$arr = array(4, 2, 4, 5, 2, 3, 1);
$arr_size = sizeof($arr, 0);
printRepeating($arr, $arr_size);
 
// This code is contributed by Ajit
?>


Javascript




<script>
    function printRepeating(arr , size)
    {
        var i, j;
        document.write("Repeating Elements are ");
        for (i = 0; i < size-1; i++)
        {
            for (j = i + 1; j < size; j++)
            {
                if (arr[i] == arr[j])
                    document.write(arr[i] + " ");
            }
        }
    }
 
var arr = [4, 2, 4, 5, 2, 3, 1];
var arr_size = arr.length;
printRepeating(arr, arr_size);
 
// This code is contributed by 29AjayKumar
</script>


Output

Repeating elements are 4 2 

Time Complexity: O(N*N), Iterating over the array of size N for all the N elements.
Auxiliary Space: O(1)

Find the two repeating elements in a given array using Visited Array:

The idea is to keep track of elements. Whenever an element is encountered that is already present then print that element.

Follow the steps below to solve the problem:

  • Create a count array of size N to keep track of elements that are visited.
  • Traverse the array once. While traversing, keep track of the count of all elements in the array using a temp array count[] of size n,
  • When an element is encountered that is already present, print that element.

Below is the implementation of the above approach:

C++




// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
void printRepeating(int arr[], int size)
{
    int* count = new int[sizeof(int) * (size - 2)];
    int i;
 
    cout << " Repeating elements are ";
    for (i = 0; i < size; i++) {
        if (count[arr[i]] == 1)
            cout << arr[i] << " ";
        else
            count[arr[i]]++;
    }
}
 
// Driver code
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    return 0;
}
 
// This is code is contributed by rathbhupendra


C




#include <stdio.h>
#include <stdlib.h>
 
void printRepeating(int arr[], int size)
{
    int* count = (int*)calloc(sizeof(int), (size - 2));
    int i;
 
    printf(" Repeating elements are ");
    for (i = 0; i < size; i++) {
        if (count[arr[i]] == 1)
            printf("%d ", arr[i]);
        else
            count[arr[i]]++;
    }
}
 
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    getchar();
    return 0;
}


Java




import java.io.*;
 
class RepeatElement {
    void printRepeating(int arr[], int size)
    {
        int count[] = new int[size];
        int i;
 
        System.out.print("Repeating elements are ");
        for (i = 0; i < size; i++) {
            if (count[arr[i]] == 1)
                System.out.print(arr[i] + " ");
            else
                count[arr[i]]++;
        }
    }
 
    public static void main(String[] args)
    {
        RepeatElement repeat = new RepeatElement();
        int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.length;
        repeat.printRepeating(arr, arr_size);
    }
}


Python3




# Python3 code for Find the two repeating
# elements in a given array
 
 
def printRepeating(arr, size):
    count = [0] * size
    print(" Repeating elements are ", end="")
    for i in range(0, size):
        if(count[arr[i]] == 1):
            print(arr[i], end=" ")
        else:
            count[arr[i]] = count[arr[i]] + 1
 
 
# Driver code
arr = [4, 2, 4, 5, 2, 3, 1]
arr_size = len(arr)
printRepeating(arr, arr_size)
 
 
# This code is contributed by Nikita Tiwari.


C#




// C# program to Find the two
// repeating elements in a given array
using System;
 
class GFG {
 
    static void printRepeating(int[] arr, int size)
    {
        int[] count = new int[size];
        int i;
 
        Console.Write("Repeating elements are ");
        for (i = 0; i < size; i++) {
            if (count[arr[i]] == 1)
                Console.Write(arr[i] + " ");
            else
                count[arr[i]]++;
        }
    }
 
    // driver code
    public static void Main()
    {
        int[] arr = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.Length;
 
        printRepeating(arr, arr_size);
    }
}
 
// This code is contributed by Sam007


PHP




<?php
// PHP program to Find the two
// repeating elements in a given array
function printRepeating($arr, $size)
{
    $count = array_fill(0, $size, 0);
    echo "Repeating elements are ";
    for ($i = 0; $i < $size; $i++)
    {
        if ($count[$arr[$i]] == 1)
            echo $arr[$i]." ";
        else
            $count[$arr[$i]]++;
    }
}
 
// Driver code
$arr = array(4, 2, 4, 5, 2, 3, 1);
$arr_size = count($arr);
 
printRepeating($arr, $arr_size);
         
// This code is contributed by mits
?>


Javascript




<script>
 
    // Javascript program to Find the two
    // repeating elements in a given array
       
    function printRepeating(arr, size)
    {
        let count = new Array(size);
        count.fill(0);
        let i;
  
        document.write("Repeating elements are ");
        for (i = 0; i < size; i++)
        {
            if (count[arr[i]] == 1)
                document.write(arr[i] + " ");
            else
                count[arr[i]]++;
        }
    }
     
    let arr = [4, 2, 4, 5, 2, 3, 1];
    let arr_size = arr.length;
 
    printRepeating(arr, arr_size);
     
</script>


Output

 Repeating elements are 4 2 

Time Complexity: O(N), Traversing the array of size N
Auxiliary Space: O(N), Count array of size N to keep track of elements

Find the two repeating elements in a given array using Mathematics:

The idea is to calculate the sum and product of elements that are repeating in the array and using those two equations find those repeating elements.

Follow the steps below to solve the problem:

  • To find the sum of repeating elements (let’s say X and Y) subtract the sum of the first N natural numbers from the total sum of the array i.e. X + Y = sum(arr) – N*(N + 1) / 2
  • Now, finding the product of repeating elements that is X*Y = P / N!, where P is the product of all elements in the array.
  • For X – Y = sqrt((X+Y)2 – 4*XY)
  • By solving these two equations X and Y will be calculated.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
/* function to get factorial of n */
int fact(int n);
 
void printRepeating(int arr[], int size)
{
    int S = 0; /* S is for sum of elements in arr[] */
    int P = 1; /* P is for product of elements in arr[] */
    int x, y; /* x and y are two repeating elements */
    int D; /* D is for difference of x and y, i.e., x-y*/
    int n = size - 2, i;
 
    /* Calculate Sum and Product of all elements in arr[] */
    for (i = 0; i < size; i++) {
        S = S + arr[i];
        P = P * arr[i];
    }
 
    S = S - n * (n + 1) / 2; /* S is x + y now */
    P = P / fact(n); /* P is x*y now */
 
    D = sqrt(S * S - 4 * P); /* D is x - y now */
 
    x = (D + S) / 2;
    y = (S - D) / 2;
 
    cout << "Repeating elements are " << x << " " << y;
}
 
int fact(int n) { return (n == 0) ? 1 : n * fact(n - 1); }
 
// Driver code
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    return 0;
}
 
// This code is contributed by rathbhupendra


Java




import java.io.*;
 
class RepeatElement {
    void printRepeating(int arr[], int size)
    {
        /* S is for sum of elements in arr[] */
        int S = 0;
 
        /* P is for product of elements in arr[] */
        int P = 1;
 
        /* x and y are two repeating elements */
        int x, y;
 
        /* D is for difference of x and y, i.e., x-y*/
        int D;
 
        int n = size - 2, i;
 
        /* Calculate Sum and Product of all elements in
         * arr[] */
        for (i = 0; i < size; i++) {
            S = S + arr[i];
            P = P * arr[i];
        }
 
        /* S is x + y now */
        S = S - n * (n + 1) / 2;
 
        /* P is x*y now */
        P = P / fact(n);
 
        /* D is x - y now */
        D = (int)Math.sqrt(S * S - 4 * P);
 
        x = (D + S) / 2;
        y = (S - D) / 2;
 
        System.out.println(
            "The two repeating elements are :");
        System.out.print(x + " " + y);
    }
 
    int fact(int n)
    {
        return (n == 0) ? 1 : n * fact(n - 1);
    }
 
    public static void main(String[] args)
    {
        RepeatElement repeat = new RepeatElement();
        int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.length;
        repeat.printRepeating(arr, arr_size);
    }
}
 
// This code has been contributed by Mayank Jaiswal


Python3




# Python3 code for Find the two repeating
# elements in a given array
import math
 
 
def printRepeating(arr, size):
 
    # S is for sum of elements in arr[]
    S = 0
 
    # P is for product of elements in arr[]
    P = 1
 
    n = size - 2
 
    # Calculate Sum and Product
    # of all elements in arr[]
    for i in range(0, size):
        S = S + arr[i]
        P = P * arr[i]
 
    # S is x + y now
    S = S - n * (n + 1) // 2
 
    # P is x*y now
    P = P // fact(n)
 
    # D is x - y now
    D = math.sqrt(S * S - 4 * P)
 
    x = (D + S) // 2
    y = (S - D) // 2
 
    print("Repeating elements are ",
          (int)(x), " ", (int)(y))
 
 
def fact(n):
    if(n == 0):
        return 1
    else:
        return(n * fact(n - 1))
 
 
# Driver code
arr = [4, 2, 4, 5, 2, 3, 1]
arr_size = len(arr)
printRepeating(arr, arr_size)
 
 
# This code is contributed by Nikita Tiwari.


C#




using System;
 
class GFG {
 
    static void printRepeating(int[] arr, int size)
    {
        /* S is for sum of elements in arr[] */
        int S = 0;
 
        /* P is for product of elements in arr[] */
        int P = 1;
 
        /* x and y are two repeating elements */
        int x, y;
 
        /* D is for difference of x and y, i.e., x-y*/
        int D;
 
        int n = size - 2, i;
 
        /* Calculate Sum and Product
         of all elements in arr[] */
        for (i = 0; i < size; i++) {
            S = S + arr[i];
            P = P * arr[i];
        }
 
        /* S is x + y now */
        S = S - n * (n + 1) / 2;
 
        /* P is x*y now */
        P = P / fact(n);
 
        /* D is x - y now */
        D = (int)Math.Sqrt(S * S - 4 * P);
 
        x = (D + S) / 2;
        y = (S - D) / 2;
 
        Console.Write("Repeating elements are ");
        Console.Write(x + " " + y);
    }
 
    static int fact(int n)
    {
        return (n == 0) ? 1 : n * fact(n - 1);
    }
 
    // driver code
    public static void Main()
    {
        int[] arr = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.Length;
 
        printRepeating(arr, arr_size);
    }
}
// This code is contributed by Sam007


PHP




<?php
 
/* function to get factorial of n */
function fact($n){
   
return ($n == 0)? 1 : $n*fact($n-1);
}
 
function printRepeating($arr, $size)
{
 $S = 0; /* S is for sum of elements in arr[] */
 $P = 1; /* P is for product of elements in arr[] */
 $x; $y; /* x and y are two repeating elements */
 $D;     /* D is for difference of x and y, i.e., x-y*/
 $n = $size - 2;
  
 
/* Calculate Sum and Product of all elements in arr[] */
for($i = 0; $i < $size; $i++)
{
    $S = $S + $arr[$i];
    $P = $P*$arr[$i];
}    
 
$S = $S - $n*($n+1)/2; /* S is x + y now */
$P = $P/fact($n);         /* P is x*y now */
 
$D = sqrt($S*$S - 4*$P); /* D is x - y now */
 
$x = ($D + $S)/2;
$y = ($S - $D)/2;
 
echo "Repeating elements are ".$x." ".$y;
}    
 
 
 
$arr = array(4, 2, 4, 5, 2, 3, 1);
$arr_size = count($arr);
printRepeating($arr, $arr_size);
?>


Javascript




<script>
 
    function printRepeating(arr , size)
    {
        /* S is for sum of elements in arr */
        var S = 0;
         
        /* P is for product of elements in arr */
        var P = 1;
         
        /* x and y are two repeating elements */
        var x, y;
         
        /* D is for difference of x and y, i.e., x-y*/
        var D;
         
        var n = size - 2, i;
 
        /* Calculate Sum and Product of all elements in arr */
        for (i = 0; i < size; i++)
        {
            S = S + arr[i];
            P = P * arr[i];
        }
 
        /* S is x + y now */
        S = S - n * parseInt((n + 1) / 2);
         
        /* P is x*y now */
        P = parseInt(P / fact(n));
        
        /* D is x - y now */
        D = parseInt( Math.sqrt(S * S - 4 * P));
         
 
        x = parseInt((D + S) / 2);
        y = parseInt((S - D) / 2);
 
        document.write("Repeating elements are " + x + " " + y);
    }
 
    function fact(n)
    {    var ans = false;
        if(n == 0)
            return 1;
        else
            return(n * fact(n - 1));
    }
 
     
    var arr = [4, 2, 4, 5, 2, 3, 1];
    var arr_size = arr.length;
    printRepeating(arr, arr_size);
 
// This code is contributed by 29AjayKumar
 
</script>


Output

Repeating elements are 4 2

Time Complexity: O(N), Traversing over the array of size N to find the sum and product of the array 
Auxiliary Space: O(1) 

Find the two repeating elements in a given array using XOR: 

The idea is to use find the XOR of the repeating elements and then find the repeating elements.

Follow the steps below to solve the problem:

  • To find the XOR of repeating elements XOR all the elements of the array and then XOR that result with XOR of the first N natural numbers.
  • Now, find the rightmost set bit of X^Y to divide the array on the basis of the rightmost set bit.
  • Let’s say x = 0 and y = 0, XOR all the numbers in the array with x whose bit is set at the rightmost position of X^Y and those numbers whose bit is not set at that position then XOR those numbers with y.
  • after this run a loop from 1 to N and check whose bit is set at that rightmost position of X^Y then XOR that number with x, otherwise XOR the number with y.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
void printRepeating(int arr[], int size)
{
    int Xor = arr[0]; /* Will hold Xor of all elements */
    int set_bit_no; /* Will have only single set bit of Xor
                     */
    int i;
    int n = size - 2;
    int x = 0, y = 0;
 
    /* Get the Xor of all elements in arr[] and {1, 2 .. n}
     */
    for (i = 1; i < size; i++)
        Xor ^= arr[i];
    for (i = 1; i <= n; i++)
        Xor ^= i;
 
    /* Get the rightmost set bit in set_bit_no */
    set_bit_no = Xor & ~(Xor - 1);
 
    /* Now divide elements in two sets by comparing
    rightmost set bit of Xor with bit at same position in
    each element. */
    for (i = 0; i < size; i++) {
        if (arr[i] & set_bit_no)
            x = x ^ arr[i]; /*Xor of first set in arr[] */
        else
            y = y ^ arr[i]; /*Xor of second set in arr[] */
    }
    for (i = 1; i <= n; i++) {
        if (i & set_bit_no)
            x = x ^ i; /*Xor of first set in arr[] and {1,
                          2, ...n }*/
        else
            y = y ^ i; /*Xor of second set in arr[] and {1,
                          2, ...n } */
    }
 
    cout << "Repeating elements are " << y << " " << x;
}
 
// Driver code
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    return 0;
}
 
// This code is contributed by rathbhupendra


C




#include <stdio.h>
 
void printRepeating(int arr[], int size)
{
    int xor = arr[0]; /* Will hold xor of all elements */
    int set_bit_no; /* Will have only single set bit of xor
                     */
    int i;
    int n = size - 2;
    int x = 0, y = 0;
 
    /* Get the xor of all elements in arr[] and {1, 2 .. n}
     */
    for (i = 1; i < size; i++)
        xor ^= arr[i];
    for (i = 1; i <= n; i++)
        xor ^= i;
 
    /* Get the rightmost set bit in set_bit_no */
    set_bit_no = xor&~(xor-1);
 
    /* Now divide elements in two sets by comparing
     rightmost set bit of xor with bit at same position in
     each element. */
    for (i = 0; i < size; i++) {
        if (arr[i] & set_bit_no)
            x = x ^ arr[i]; /*XOR of first set in arr[] */
        else
            y = y ^ arr[i]; /*XOR of second set in arr[] */
    }
    for (i = 1; i <= n; i++) {
        if (i & set_bit_no)
            x = x ^ i; /*XOR of first set in arr[] and {1,
                          2, ...n }*/
        else
            y = y ^ i; /*XOR of second set in arr[] and {1,
                          2, ...n } */
    }
 
    printf("Repeating elements are %d %d ", y, x);
}
 
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    getchar();
    return 0;
}


Java




import java.io.*;
 
class RepeatElement {
    void printRepeating(int arr[], int size)
    {
        /* Will hold xor of all elements */
        int xor = arr[0];
 
        /* Will have only single set bit of xor */
        int set_bit_no;
 
        int i;
        int n = size - 2;
        int x = 0, y = 0;
 
        /* Get the xor of all elements in arr[] and {1, 2 ..
         * n} */
        for (i = 1; i < size; i++)
            xor ^= arr[i];
        for (i = 1; i <= n; i++)
            xor ^= i;
 
        /* Get the rightmost set bit in set_bit_no */
        set_bit_no = (xor & ~(xor - 1));
 
        /* Now divide elements in two sets by comparing
           rightmost set bit of xor with bit at same
           position in each element. */
        for (i = 0; i < size; i++) {
            int a = arr[i] & set_bit_no;
            if (a != 0)
                x = x
                    ^ arr[i]; /*XOR of first set in arr[] */
            else
                y = y ^ arr[i]; /*XOR of second set in arr[]
                                 */
        }
        for (i = 1; i <= n; i++) {
            int a = i & set_bit_no;
            if (a != 0)
                x = x ^ i; /*XOR of first set in arr[] and
                              {1, 2, ...n }*/
            else
                y = y ^ i; /*XOR of second set in arr[] and
                              {1, 2, ...n } */
        }
 
        System.out.print("Repeating elements are ");
        System.out.println(y + " " + x);
    }
 
    /* Driver program to test the above function */
    public static void main(String[] args)
    {
        RepeatElement repeat = new RepeatElement();
        int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.length;
        repeat.printRepeating(arr, arr_size);
    }
}
 
// This code has been contributed by Mayank Jaiswal


Python3




# Python3 code to Find the
# two repeating elements
# in a given array
 
 
def printRepeating(arr, size):
 
    # Will hold xor
    # of all elements
    xor = arr[0]
    n = size - 2
    x = 0
    y = 0
 
    # Get the xor of all
    # elements in arr[]
    # and 1, 2 .. n
    for i in range(1, size):
        xor ^= arr[i]
    for i in range(1, n + 1):
        xor ^= i
 
    # Get the rightmost set
    # bit in set_bit_no
    set_bit_no = xor & ~(xor-1)
 
    # Now divide elements in two
    # sets by comparing rightmost
    # set bit of xor with bit at
    # same position in each element.
    for i in range(0, size):
 
        if(arr[i] & set_bit_no):
 
            # XOR of first
            # set in arr[]
            x = x ^ arr[i]
        else:
 
            # XOR of second
            # set in arr[]
            y = y ^ arr[i]
 
    for i in range(1, n + 1):
 
        if(i & set_bit_no):
 
            # XOR of first set
            # in arr[] and
            # 1, 2, ...n
            x = x ^ i
        else:
 
             # XOR of second set
             # in arr[] and
             # 1, 2, ...n
            y = y ^ i
 
    print("Repeating elements are", y, x)
 
 
# Driver code
arr = [4, 2, 4,
       5, 2, 3, 1]
arr_size = len(arr)
printRepeating(arr, arr_size)
 
# This code is contributed
# by Smitha


C#




using System;
 
class GFG {
    static void printRepeating(int[] arr, int size)
    {
        /* Will hold xor of all elements */
        int xor = arr[0];
 
        /* Will have only single set bit of xor */
        int set_bit_no;
 
        int i;
        int n = size - 2;
        int x = 0, y = 0;
 
        /* Get the xor of all elements
         in arr[] and {1, 2 .. n} */
        for (i = 1; i < size; i++)
            xor ^= arr[i];
 
        for (i = 1; i <= n; i++)
            xor ^= i;
 
        /* Get the rightmost set bit in set_bit_no */
        set_bit_no = (xor & ~(xor - 1));
 
        /* Now divide elements in two sets by
         comparing rightmost set bit of xor with bit
         at same position in each element. */
        for (i = 0; i < size; i++) {
            int a = arr[i] & set_bit_no;
 
            if (a != 0)
                /* XOR of first set in arr[] */
                x = x ^ arr[i];
            else
                /* XOR of second set in arr[] */
                y = y ^ arr[i];
        }
        for (i = 1; i <= n; i++) {
            int a = i & set_bit_no;
 
            if (a != 0)
 
                /* XOR of first set in
                 arr[] and {1, 2, ...n }*/
                x = x ^ i;
            else
 
                /* XOR of second set in
                 arr[] and {1, 2, ...n } */
                y = y ^ i;
        }
 
        Console.Write("Repeating elements are ");
        Console.Write(y + " " + x);
    }
 
    /* Driver program to test the above function */
    public static void Main()
    {
        int[] arr = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.Length;
 
        printRepeating(arr, arr_size);
    }
}
 
// This code is contributed by Sam007


PHP




<?php
// PHP code to Find the
// two repeating elements
// in a given array
function printRepeating( $arr, $size)
{
    $xor = $arr[0]; /* Will hold xor of all elements */
    $set_bit_no; /* Will have only single set bit of xor */
    $i;
    $n = $size - 2;
    $x = 0; $y = 0;
     
    /* Get the xor of all elements in arr[] and {1, 2 .. n} */
    for($i = 1; $i < $size; $i++)
    $xor ^= $arr[$i];
    for($i = 1; $i <= $n; $i++)
    $xor ^= $i;
     
    /* Get the rightmost set bit in set_bit_no */
    $set_bit_no = $xor & ~($xor-1);
     
    /* Now divide elements in two sets by
    comparing rightmost set bit of xor with
    bit at same position in each element. */
    for($i = 0; $i < $size; $i++)
    {
        if($arr[$i] & $set_bit_no)
        $x = $x ^ $arr[$i]; /*XOR of first set in arr[] */
        else
        $y = $y ^ $arr[$i]; /*XOR of second set in arr[] */
         
    }
    for($i = 1; $i <= $n; $i++)
    {
        if($i & $set_bit_no)
        /*XOR of first set in arr[] and {1, 2, ...n }*/
        $x = $x ^ $i;
        else
        /*XOR of second set in arr[] and {1, 2, ...n } */
        $y = $y ^ $i;
         
    }
    echo "Repeating elements are ";
    echo $y. " ".$x;
     
}
 
$arr = array(4, 2, 4, 5, 2, 3, 1);
$arr_size = count($arr);
printRepeating($arr, $arr_size);
 
// This code has been contributed by Rajput-Ji
?>


Javascript




<script>
 
function printRepeating( arr, size)
{
    let Xor = arr[0]; /* Will hold Xor of all elements */
    let set_bit_no; /* Will have only single set bit of Xor */
    let i;
    let n = size - 2;
    let x = 0, y = 0;
         
    /* Get the Xor of all elements in arr[] and {1, 2 .. n} */
    for(i = 1; i < size; i++)
        Xor ^= arr[i];
    for(i = 1; i <= n; i++)
        Xor ^= i;
     
    /* Get the rightmost set bit in set_bit_no */
    set_bit_no = Xor & ~(Xor-1);
     
    /* Now divide elements in two sets by comparing rightmost set
    bit of Xor with bit at same position in each element. */
    for(i = 0; i < size; i++)
    {
        if(arr[i] & set_bit_no)
        x = x ^ arr[i]; /*Xor of first set in arr[] */
        else
        y = y ^ arr[i]; /*Xor of second set in arr[] */
    }
    for(i = 1; i <= n; i++)
    {
        if(i & set_bit_no)
        x = x ^ i; /*Xor of first set in arr[] and {1, 2, ...n }*/
        else
        y = y ^ i; /*Xor of second set in arr[] and {1, 2, ...n } */
    }
         
    document.write("Repeating elements are "+y+" "+x);
}
    // driver code
    let arr = [4, 2, 4, 5, 2, 3, 1];
    let arr_size = arr.length;
    printRepeating(arr, arr_size);
     
    // This code is contributed by jana_sayantan.
</script>


Output

Repeating elements are 4 2

Time Complexity: O(N), Linear Traversals are performed over the array of size N.
Auxiliary Space: O(1) 

Find the two repeating elements in a given array using Array Elements as an Index:

The idea is to use the original array to mark the elements in the array by making them negative and when an index is found which is already marked then that index would be our possible answer.

Follow the steps below to solve the problem:

  • Traverse over the array and go to index arr[i] and make it negative.
  • If that number is already negative then that index(i.e. arr[i]) is a repeating element.
  • Take absolute value while marking indexes may be the current number is negative.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
void printRepeating(int arr[], int size)
{
    int i;
 
    cout << "Repeating elements are ";
 
    for (i = 0; i < size; i++) {
        if (arr[abs(arr[i])] > 0)
            arr[abs(arr[i])] = -arr[abs(arr[i])];
        else
            cout << abs(arr[i]) << " ";
    }
}
 
// Driver code
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    return 0;
}
 
// This code is contributed by rathbhupendra


C




#include <stdio.h>
#include <stdlib.h>
 
void printRepeating(int arr[], int size)
{
    int i;
 
    printf("Repeating elements are");
 
    for (i = 0; i < size; i++) {
        if (arr[abs(arr[i])] > 0)
            arr[abs(arr[i])] = -arr[abs(arr[i])];
        else
            printf(" %d", abs(arr[i]));
    }
}
 
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    getchar();
    return 0;
}


Java




import java.io.*;
 
class RepeatElement {
    void printRepeating(int arr[], int size)
    {
        int i;
        System.out.print("Repeating elements are ");
 
        for (i = 0; i < size; i++) {
            int abs_val = Math.abs(arr[i]);
            if (arr[abs_val] > 0)
                arr[abs_val] = -arr[abs_val];
            else
                System.out.print(abs_val + " ");
        }
    }
 
    /* Driver program to test the above function */
    public static void main(String[] args)
    {
        RepeatElement repeat = new RepeatElement();
        int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.length;
        repeat.printRepeating(arr, arr_size);
    }
}
 
// This code has been contributed by Mayank Jaiswal


Python3




# Python3 code for Find the two repeating
# elements in a given array
 
 
def printRepeating(arr, size):
 
    print("Repeating elements are", end=" ")
 
    for i in range(0, size):
 
        if(arr[abs(arr[i])] > 0):
            arr[abs(arr[i])] = (-1) * arr[abs(arr[i])]
        else:
            print(abs(arr[i]), end=" ")
 
 
# Driver code
arr = [4, 2, 4, 5, 2, 3, 1]
arr_size = len(arr)
printRepeating(arr, arr_size)
 
 
# This code is contributed by Nikita Tiwari.


C#




// C# code for Find the two repeating
// elements in a given array
using System;
 
class GFG {
    static void printRepeating(int[] arr, int size)
    {
        int i;
        Console.Write("Repeating elements are ");
 
        for (i = 0; i < size; i++) {
            int abs_val = Math.Abs(arr[i]);
            if (arr[abs_val] > 0)
                arr[abs_val] = -arr[abs_val];
            else
                Console.Write(abs_val + " ");
        }
    }
 
    /* Driver program to test the above function */
    public static void Main()
    {
        int[] arr = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.Length;
 
        printRepeating(arr, arr_size);
    }
}
 
// This code is contributed by Sam007


PHP




<?php
 
 
function  printRepeating($arr, $size)
{
    $i;
 
 echo "Repeating elements are"," ";
 
for($i = 0; $i < $size; $i++)
{
    if($arr[abs($arr[$i])] > 0)
    $arr[abs($arr[$i])] = -$arr[abs($arr[$i])];
    else
    echo  abs($arr[$i])," ";
}        
}    
 
 
    $arr = array (4, 2, 4, 5, 2, 3, 1);
    $arr_size = sizeof($arr);
    printRepeating($arr, $arr_size);
     
     
#This code is contributed by aj_36
?>


Javascript




<script>
 
function printRepeating(arr , size)
{
    var i; 
    document.write("Repeating elements are ");
    
        for(i = 0; i < size; i++)
        {
            var abs_val = Math.abs(arr[i]);
            if(arr[abs_val] > 0)x
                arr[abs_val] = -arr[abs_val];
            else
                document.write(abs_val + " ");
    }        
}
 
/* Driver program to test the above function */
  
var arr = [4, 2, 4, 5, 2, 3, 1];
var arr_size = arr.length;
printRepeating(arr, arr_size);
 
// This code is contributed by 29AjayKumar
 
</script>


Output

Repeating elements are 4 2 

Time Complexity: O(N), Traversing over the array of size N. 
Auxiliary Space: O(1) 

Note: This method modifies the original array and may not be a recommended method if it’s not allowed to modify the array. 

Find the two repeating elements in a given array by Modifying Original Array:

The idea is to increment every element at (arr[i] – 1)th index by N-1 (as the elements are present up to N-2 only) 

Follow the steps below to solve the problem:

  • incrementing each element at (arr[i]th-1) index by N-1
  • so when this incremented element is divided by N-1 it will give a number of times we have added N-1 to it,
  • check if the element at that index when divided by (N-1) gives 2
  • If this is true then it means that the element has appeared twice

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
void twoRepeated(int arr[], int N)
{
    int m = N - 1;
    for (int i = 0; i < N; i++) {
        arr[arr[i] % m - 1] += m;
        if ((arr[arr[i] % m - 1] / m) == 2)
            cout << arr[i] % m << " ";
    }
}
// Driver Code
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Repeating elements are ";
    twoRepeated(arr, n);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




#include <stdio.h>
 
void twoRepeated(int arr[], int N)
{
    int m = N - 1;
    for (int i = 0; i < N; i++) {
        arr[arr[i] % m - 1] += m;
        if ((arr[arr[i] % m - 1] / m) == 2)
            printf("%d ", arr[i] % m);
    }
}
// Driver Code
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Repeating elements are ");
    twoRepeated(arr, n);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




import java.io.*;
 
class GFG {
 
    public static void twoRepeated(int arr[], int N)
    {
        int m = N - 1;
        for (int i = 0; i < N; i++) {
            arr[arr[i] % m - 1] += m;
 
            if ((arr[arr[i] % m - 1] / m) == 2)
                System.out.print(arr[i] % m + " ");
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
        int n = 7;
        System.out.print("Repeating elements are ");
        twoRepeated(arr, n);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python program for the above approach
def twoRepeated(arr, N):
    m = N - 1
    for i in range(N):
        arr[arr[i] % m - 1] += m
        if ((arr[arr[i] % m - 1] // m) == 2):
            print(arr[i] % m, end=" ")
 
 
# Driver Code
arr = [4, 2, 4, 5, 2, 3, 1]
n = len(arr)
print("Repeating elements are ", end="")
twoRepeated(arr, n)
 
# This code is contributed by Shubham Singh


C#




// C# program for the above approach
using System;
 
public class GFG {
    public static void twoRepeated(int[] arr, int N)
    {
        int m = N - 1;
        for (int i = 0; i < N; i++) {
            arr[arr[i] % m - 1] += m;
 
            if ((arr[arr[i] % m - 1] / m) == 2)
                Console.Write(arr[i] % m + " ");
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { 4, 2, 4, 5, 2, 3, 1 };
        int n = 7;
 
        Console.Write("Repeating elements are ");
 
        twoRepeated(arr, n);
    }
}
 
// This code is contributed by splevel62.


Javascript




<script>
 
function twoRepeated(arr, N)
{
    let m = N - 1;
    for(let i = 0; i < N; i++)
    {
        arr[parseInt(arr[i] % m) - 1] += m;
        if (parseInt(arr[parseInt(arr[i] % m) - 1] / m) == 2)
            document.write(parseInt(arr[i] % m) + " ");
    }
}
 
// Driver Code
var arr = [ 4, 2, 4, 5, 2, 3, 1 ];
var n = 7;
document.write("Repeating elements are ");
 
twoRepeated(arr, n);
 
// This code is contributed by Potta Lokesh
 
</script>


Output

Repeating elements are 4 2 

Time Complexity: O(N), Traversing over the array of size N. 
Auxiliary Space: O(1) 

Find the two repeating elements in a given array using Hash Set:

The idea is to use a set, insert the elements in the set, and check simultaneously whether that is already present the set or not.

Follow the steps below to solve the problem:

  • Traverse over the array and check whether the ith element is present in the set or not.
  • If it present then print that element
  • Otherwise that element into the set. 

Below is the implementation of the above approach:

C++




// C++ program to Find the two repeating
// elements in a given array
#include <bits/stdc++.h>
using namespace std;
 
void printRepeating(int arr[], int size)
{
    unordered_set<int> s;
    cout << "Repeating elements are ";
    for (int i = 0; i < size; i++) {
        if (s.empty() == false && s.find(arr[i]) != s.end())
            cout << arr[i] << "  ";
        s.insert(arr[i]);
    }
}
 
// Driver code
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    return 0;
}
 
// This code is contributed by nakul amate


Java




// Java program to Find the two repeating
// elements in a given array
import java.util.*;
class GFG {
 
    static void printRepeating(int arr[], int size)
    {
        HashSet<Integer> s = new HashSet<>();
        System.out.print("Repeating elements are ");
        for (int i = 0; i < size; i++) {
            if (!s.isEmpty() && s.contains(arr[i]))
                System.out.print(arr[i] + "  ");
            s.add(arr[i]);
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.length;
        printRepeating(arr, arr_size);
    }
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program to find the two repeating
# elements in a given array
 
 
def printRepeating(arr, size):
 
    s = set()
    print("Repeating elements are ", end="")
 
    for i in range(size):
        if (len(s) and arr[i] in s):
            print(arr[i], end="  ")
 
        s.add(arr[i])
 
 
# Driver code
arr = [4, 2, 4, 5, 2, 3, 1]
arr_size = len(arr)
printRepeating(arr, arr_size)
 
# This code is contributed by Shubham Singh


C#




// C# program to Find the two repeating
// elements in a given array
using System;
using System.Collections.Generic;
 
public class GFG {
 
    static void printRepeating(int[] arr, int size)
    {
        HashSet<int> s = new HashSet<int>();
        Console.Write("Repeating elements are ");
        for (int i = 0; i < size; i++) {
            if (s.Count != 0 && s.Contains(arr[i]))
                Console.Write(arr[i] + "  ");
            s.Add(arr[i]);
        }
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.Length;
        printRepeating(arr, arr_size);
    }
}
 
// This code is contributed by Shubham Singh


Javascript




<script>
 
function printRepeating(arr, size)
{
    const s = new Set();
    document.write("Repeating elements are ");
    for(let i = 0; i < size; i++)
    {
      if(s.size != 0 && s.has(arr[i]))
        document.write(arr[i] + " ");
      s.add(arr[i]);
             
    }
}
 
// Driver Code
var arr = [ 4, 2, 4, 5, 2, 3, 1 ];
var arr_size = 7;
printRepeating(arr, arr_size);
 
// This code is contributed by Shubham Singh
 
</script>


Output

Repeating elements are 4  2  

Time Complexity: O(N), Traversing over the array of size N.  
Auxiliary Space: O(N), Space used to store the elements in the hash set

Find the two repeating elements in a given array using Sorting:

The idea is to sort the given array and then traverse it. While traversing find if two consecutive elements are equal then that is the repeating element.

Code-

C++




// C++ program to Find the two repeating
// elements in a given array
#include <bits/stdc++.h>
using namespace std;
 
void printRepeating(int arr[], int size)
{
    sort(arr,arr+size);
    cout << "Repeating elements are ";
    for (int i = 0; i < size-1; i++) {
        if (arr[i]==arr[i+1]){
             cout << arr[i] << "  ";
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    printRepeating(arr, arr_size);
    return 0;
}


Java




// Java program to Find the two repeating
// elements in a given array
import java.util.Arrays;
 
public class Main {
    static void printRepeating(int arr[], int size) {
        Arrays.sort(arr);
        System.out.print("Repeating elements are ");
        for (int i = 0; i < size-1; i++) {
            if (arr[i] == arr[i+1]) {
                System.out.print(arr[i] + " ");
            }
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
        int arr_size = arr.length;
        printRepeating(arr, arr_size);
    }
}
 
// This code is contributed by Prajwal Kandekar


Python3




# Function to print the repeating elements in an array
def printRepeating(arr):
    arr.sort()
    print("Repeating elements are ", end="")
    for i in range(len(arr) - 1):
        if arr[i] == arr[i + 1]:
            print(arr[i], end=" ")
 
 
# Driver code
if __name__ == "__main__":
    arr = [4, 2, 4, 5, 2, 3, 1]
    printRepeating(arr)


Javascript




// JavaScript program to Find the two repeating
// elements in a given array
 
function printRepeating(arr) {
  
 // Sorting the arary
  arr.sort();
  process.stdout.write("Repeating elements are ");
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] == arr[i + 1]) {
    // Printing the answer
      process.stdout.write(arr[i] + " ");
    }
  }
}
 
// Driver code
let arr = [4, 2, 4, 5, 2, 3, 1];
printRepeating(arr);


C#




using System;
using System.Linq;
 
class Program
{
    static void PrintRepeating(int[] arr, int size)
    {
        Array.Sort(arr);
        Console.Write("Repeating elements are ");
        for (int i = 0; i < size - 1; i++)
        {
            if (arr[i] == arr[i + 1])
            {
                Console.Write(arr[i] + " ");
            }
        }
    }
 
    static void Main(string[] args)
    {
        int[] arr = { 4, 2, 4, 5, 2, 3, 1 };
        int arrSize = arr.Length;
        PrintRepeating(arr, arrSize);
    }
}


Output

Repeating elements are 2  4  

Time Complexity: O(NlogN), because of sorting  
Auxiliary Space: O(1)

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments