Open In App

Find the repeating element in an Array of size N consisting of first M natural numbers

Last Updated : 24 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, which contains a permutation of numbers from 1 to M, as well as an element that is repeated(one or more times), the task is to find the repeating element.

Examples:

Input: arr[]={2, 6, 4, 3, 1, 5, 2}, N=7
Output:
2
Explanation: In arr[], all elements from 0 to 6 occurs once, except 2 which is repeated once.

Input: arr[]={2, 1, 3, 1, 1, 1}, N=6
Output:
1

Naive Approach: The naive approach would be to sort the array and check for adjacent elements that are equal.

C++




// C++ program to find the repeating element
// in an array using naive approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the repeating element
int findRepeatingElement(int arr[], int n, int m) {
    // Sort the given array
    sort(arr, arr + n);
   
    // Traverse the sorted array to find the repeating
    // element
    for (int i = 0; i < n-1; i++) {
        if (arr[i] == arr[i + 1]) {
            return arr[i];
        }
    }
 
    // If no repeating element found
    return -1;
}
 
// Driver code
int main() {
      // Input array
    int arr[] = { 2, 6, 4, 3, 1, 5, 2 };
       
    int n = sizeof(arr) / sizeof(arr[0]);
    int m = 4;
      
      // Function call to find the repeating element
    int repeating_element = findRepeatingElement(arr, n, m);
 
    // Print the repeating element
    cout<< repeating_element << endl;
 
    return 0;
}


Java




// Java program to find the repeating element
// in an array using naive approach
 
import java.util.Arrays;
 
public class GFG {
    // Function to find the repeating element
    public static int findRepeatingElement(int[] arr, int n, int m) {
        // Sort the given array
        Arrays.sort(arr);
 
        // Traverse the sorted array to find the repeating element
        for (int i = 0; i < n - 1; i++) {
            if (arr[i] == arr[i + 1]) {
                return arr[i];
            }
        }
 
        // If no repeating element found
        return -1;
    }
 
    // Driver code
    public static void main(String[] args) {
        // Input array
        int[] arr = { 2, 1, 3, 1, 1, 1};
        int n = arr.length;
        int m = 4;
 
        // Function call to find the repeating element
        int repeating_element = findRepeatingElement(arr, n, m);
 
        // Print the repeating element
        System.out.println(repeating_element);
    }
}


Python3




def find_repeating_element(arr, n, m):
    arr.sort()
    for i in range(n - 1):
        if arr[i] == arr[i + 1]:
            return arr[i]
    return -1
# Input array
arr = [2, 6, 4, 3, 1, 5, 2]
n = len(arr)
m = 4
 
# Function call to find the repeating element
repeating_element = find_repeating_element(arr, n, m)
# Print the repeating element
print(repeating_element)
 
# This code is contributed by shivhack999


C#




using System;
 
class Program
{
 
  // Function to find the repeating element
  static int findRepeatingElement(int[] arr, int n, int m)
  {
 
    // Sort the given array
    Array.Sort(arr);
 
    // Traverse the sorted array to find the repeating
    // element
    for (int i = 0; i < n-1; i++) {
      if (arr[i] == arr[i + 1]) {
        return arr[i];
      }
    }
 
    // If no repeating element found
    return -1;
  }
 
  // Driver code
  static void Main(string[] args)
  {
     
    // Input array
    int[] arr = { 2, 6, 4, 3, 1, 5, 2 };
    int n = arr.Length;
    int m = 4;
 
    // Function call to find the repeating element
    int repeating_element = findRepeatingElement(arr, n, m);
 
    // Print the repeating element
    Console.WriteLine(repeating_element);
  }
}


Javascript




// Function to find the repeating element
function findRepeatingElement(arr, n, m) {
    // Sort the given array
    arr.sort();
   
    // Traverse the sorted array to find the repeating
    // element
    for (let i = 0; i < n-1; i++) {
        if (arr[i] == arr[i + 1]) {
            return arr[i];
        }
    }
 
    // If no repeating element found
    return -1;
}
 
// Input array
let arr = [2, 6, 4, 3, 1, 5, 2];
let n = arr.length;
let m = 4;
      
// Function call to find the repeating element
let repeating_element = findRepeatingElement(arr, n, m);
 
// Print the repeating element
console.log(repeating_element);


Output

2

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

Approach: Follow the steps below to solve the problem:

  1. Initialize two variables M and sum to store the maximum element and the sum of the array respectively.
  2. Traverse array arr and do the following:
    1. Add the current element to sum
    2. Compare the current element to M to calculate the maximum element.
  3. Store the sum of permutation from 1 to M in a variable say, sum1, using the formula:
Sum of elements from 1 to X= X*(X+1)/2
  1. Calculate the answer as the difference between sum and sum1 divided by the number of extra characters i.e. (sum-sum1)/(N-M).

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the repeating character in a given
// permutation
int repeatingElement(int arr[], int N)
{
    // variables to store maximum element and sum of the
    // array respectively.
    int M = 0, sum = 0;
    for (int i = 0; i < N; i++) {
 
        // calculate sum of array
        sum += arr[i];
 
        // calculate maximum element in the array
        M = max(M, arr[i]);
    }
 
    // calculating sum of permutation
    int sum1 = M * (M + 1) / 2;
 
    // calculate required answer
    int ans = (sum - sum1) / (N - M);
    return ans;
}
// Driver code
int main()
{
    // Input
    int arr[] = { 2, 6, 4, 3, 1, 5, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << repeatingElement(arr, N) << endl;
    return 0;
}


Java




// Java Program for the above approach
import java.io.*;
 
class GFG
{
   
  // Function to calculate the repeating character in a given
  // permutation
  public static int repeatingElement(int arr[], int N)
  {
     
    // variables to store maximum element and sum of the
    // array respectively.
    int M = 0, sum = 0;
    for (int i = 0; i < N; i++) {
 
      // calculate sum of array
      sum += arr[i];
 
      // calculate maximum element in the array
      M = Math.max(M, arr[i]);
    }
 
    // calculating sum of permutation
    int sum1 = M * (M + 1) / 2;
 
    // calculate required answer
    int ans = (sum - sum1) / (N - M);
    return ans;
  }
 
  // Driver code
  public static void main (String[] args)
  {
     
    // Input
    int arr[] = { 2, 6, 4, 3, 1, 5, 2 };
    int N = arr.length;
 
    // Function call
    System.out.println(repeatingElement(arr, N));
  }
}
 
// This code is contributed by lokeshpotta20


Python3




# Python 3 program for the above approach
 
# Function to calculate the repeating character in a given
# permutation
def repeatingElement(arr, N):
   
    # variables to store maximum element and sum of the
    # array respectively.
    M = 0
    sum = 0
    for i in range(N):
       
        # calculate sum of array
        sum += arr[i]
 
        # calculate maximum element in the array
        M = max(M, arr[i])
 
    # calculating sum of permutation
    sum1 = M * (M + 1) // 2
 
    # calculate required answer
    ans = (sum - sum1) // (N - M)
    return ans
 
# Driver code
if __name__ == '__main__':
   
    # Input
    arr = [2, 6, 4, 3, 1, 5, 2]
    N = len(arr)
 
    # Function call
    print(repeatingElement(arr, N))
     
    # This code is contributed by SURENDRA_GANGWAR.


C#




// C++ program for the above approach
using System;
 
// Function to calculate the repeating character in a given
// permutation
public class GFG
{
    public static int repeatingElement(int[] arr, int N)
    {
       
        // variables to store maximum element and sum of the
        // array respectively.
        int M = 0, sum = 0;
        for (int i = 0; i < N; i++) {
 
            // calculate sum of array
            sum += arr[i];
 
            // calculate maximum element in the array
            M = Math.Max(M, arr[i]);
        }
 
        // calculating sum of permutation
        int sum1 = M * (M + 1) / 2;
 
        // calculate required answer
        int ans = (sum - sum1) / (N - M);
        return ans;
    }
   
    // Driver code
    public static void Main()
    {
        // Input
        int[] arr = { 2, 6, 4, 3, 1, 5, 2 };
        int N = 7;
 
        // Function call
        Console.WriteLine(repeatingElement(arr, N));
    }
}
 
// This code is contributed by Sohom Das


Javascript




// JavaScript program for the above approach
 
        // Function to calculate the repeating character in a given
        // permutation
        function repeatingElement(arr, N)
        {
         
            // variables to store maximum element and sum of the
            // array respectively.
            let M = 0, sum = 0;
            for (let i = 0; i < N; i++) {
 
                // calculate sum of array
                sum += arr[i];
 
                // calculate maximum element in the array
                M = Math.max(M, arr[i]);
            }
 
            // calculating sum of permutation
            let sum1 = parseInt(M * (M + 1) / 2);
 
            // calculate required answer
            let ans = parseInt((sum - sum1) / (N - M));
            return ans;
        }
        // Driver code
 
        // Input
        let arr = [2, 6, 4, 3, 1, 5, 2];
        let N = arr.length;
 
        // Function call
        document.write(repeatingElement(arr, N));
 
  // This code is contributed by Potta Lokesh
    </script>


 
 

Output

2

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



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

Similar Reads