Skip to content
Related Articles

Related Articles

Find the only repetitive element between 1 to n-1

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 08 Aug, 2022

We are given an array arr[] of size n. Numbers are from 1 to (n-1) in random order. The array has only one repetitive element. We need to find the repetitive element.

Examples:

Input  : a[] = {1, 3, 2, 3, 4}
Output : 3

Input  : a[] = {1, 5, 1, 2, 3, 4}
Output : 1

Method 1 (Simple) We use two nested loops. The outer loop traverses through all elements and the inner loop check if the element picked by the outer loop appears anywhere else.
Below is the implementation of the above approach:

C++




// CPP program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
#include <bits/stdc++.h>
using namespace std;
 
int findRepeating(int arr[], int n)
{
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (arr[i] == arr[j])
                return arr[i];
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findRepeating(arr, n);
    return 0;
}
// This code is added by Arpit Jain

Java




// Java program to find the only repeating
// element in an array where elements are
// from 1 to n-1.using System;
public class GFG {
  static int findRepeating(int[] arr)
  {
    for (int i = 0; i < arr.length; i++) {
      for (int j = i + 1; j < arr.length; j++) {
        if (arr[i] == arr[j])
          return arr[i];
      }
    }
    return -1;
  }
 
  // Driver code
  static public void main(String[] args)
  {
     
    // Code
    int[] arr
      = new int[] { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int repeatingNum = findRepeating(arr);
    System.out.println(repeatingNum);
  }
}
 
// This code is contributed by phasing17

Python3




# Python3 program to find the only
# repeating element in an array where
# elements are from 1 to n-1.
def findRepeating(arr, n):
    for i in range(n):
      for j in range(i + 1, n):
        if (arr[i] == arr[j]):
          return arr[i];
         
# Driver Code
arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
n = len(arr)
print(findRepeating(arr, n))
 
# This code is contributed by Arpit Jain

C#




// C# program to find the only repeating
// element in an array where elements are
// from 1 to n-1.using System;
 
public class GFG {
    static int findRepeating(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++) {
            for (int j = i + 1; j < arr.Length; j++) {
                if (arr[i] == arr[j])
                    return arr[i];
            }
        }
        return -1;
    }
 
    // Driver code
 
    static public void Main()
    {
        // Code
        int[] arr = new int[] { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int repeatingNum = findRepeating(arr);
        Console.WriteLine(repeatingNum);
    }
}
 
// This code is contributed by Mohd Nizam

Output

8

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

Method 2 (Using Sorting)

  • first sort the array and just compare the array element with its index 
  • if arr[i] != i+1, it means that arr[i] is repetitive. 
    • So Just return arr[I] 
  • Otherwise, array does not contain duplicates from 1 to n-1
    • In this case return -1  

C++




// CPP program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
#include <bits/stdc++.h>
using namespace std;
 
int findRepeating(int arr[], int n)
{
    sort(arr, arr + n); // sort array
    for (int i = 0; i <= n; i++) {
        // compare array element with its index
        if (arr[i] != i + 1) {
            return arr[i];
        }
    }
    return -1;
}
 
// driver code
int main()
{
    int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findRepeating(arr, n);
    return 0;
}
// this code is contributed by devendra solunke

Java




// Java program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
 
import java.util.Arrays;
 
public class GFG {
  static int findRepeating(int[] arr,int n)
  {
    Arrays.sort(arr); // sort array
    for (int i = 0; i <= n; i++) {
        // compare array element with its index
        if (arr[i] != i + 1) {
            return arr[i];
        }
    }
    return -1;
  }
 
  // Driver code
  static public void main(String[] args)
  {
     
    // Code
    int[] arr = new int[] { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int n = arr.length;
    int repeatingNum = findRepeating(arr,n);
    System.out.println(repeatingNum);
  }
}
 
// This code is contributed by Abhijeet Kumar(abhijeet19403)

Python3




# Python3 program to find the only
# repeating element in an array where
# elements are from 1 to n-1.
def findRepeating(arr, n):
    arr.sort()
    for i in range(1,n+1):
      if(arr[i] != i+1):
        return arr[i]
         
# Driver Code
arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
n = len(arr)
print(findRepeating(arr, n))
 
# This code is contributed by Arpit Jain

C#




// C# program to find the only repeating element in an array
// where elements are from 1 to n-1.
 
using System;
 
public class GFG {
 
    static int findRepeating(int[] arr, int n)
    {
        Array.Sort(arr); // sort array
        for (int i = 0; i <= n; i++) {
            // compare array element with its index
            if (arr[i] != i + 1) {
                return arr[i];
            }
        }
        return -1;
    }
 
    static public void Main()
    {
 
        // Code
        int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int n = arr.Length;
        int repeatingNum = findRepeating(arr, n);
        Console.WriteLine(repeatingNum);
    }
}
 
// This code is contributed by lokesh (lokeshmvs21).

Output

8

Time complexity: O(N*log N)  compare every array element with its index
Auxiliary Space: O(1)

Method 3 (Using Sum Formula): We know sum of first n-1 natural numbers is (n – 1)*n/2. We compute sum of array elements and subtract natural number sum from it to find the only missing element.

C++




// CPP program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
#include <bits/stdc++.h>
using namespace std;
 
int findRepeating(int arr[], int n)
{
   // Find array sum and subtract sum
   // first n-1 natural numbers from it
   // to find the result.
   return accumulate(arr , arr+n , 0) -
                   ((n - 1) * n/2);
}
 
// driver code
int main()
{  
    int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findRepeating(arr, n);
    return 0;
}

Java




// Java program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
import java.io.*;
import java.util.*;
 
class GFG
{
 
    static int findRepeating(int[] arr, int n)
    {
        // Find array sum and subtract sum
        // first n-1 natural numbers from it
        // to find the result.
 
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += arr[i];
        return sum - (((n - 1) * n) / 2);
    }
 
    // Driver code
    public static void main(String args[])
    {
        int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int n = arr.length;
        System.out.println(findRepeating(arr, n));
    }
}
 
// This code is contributed by rachana soma

Python3




# Python3 program to find the only
# repeating element in an array where
# elements are from 1 to n-1.
 
def findRepeating(arr, n):
     
    # Find array sum and subtract sum
    # first n-1 natural numbers from it
    # to find the result.
    return sum(arr) -(((n - 1) * n) // 2)
 
# Driver Code
arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
n = len(arr)
print(findRepeating(arr, n))
 
# This code is contributed
# by mohit kumar

C#




// C# program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
using System;
 
class GFG
{
 
    static int findRepeating(int[] arr, int n)
    {
        // Find array sum and subtract sum
        // first n-1 natural numbers from it
        // to find the result.
 
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += arr[i];
        return sum - (((n - 1) * n) / 2);
    }
 
    // Driver code
    public static void Main(String []args)
    {
        int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int n = arr.Length;
        Console.WriteLine(findRepeating(arr, n));
    }
}
 
/* This code contributed by PrinciRaj1992 */

Javascript




<script>
// javascript program to find the only repeating
// element in an array where elements are
// from 1 to n-1.   
function findRepeating(arr , n)
{
 
        // Find array sum and subtract sum
        // first n-1 natural numbers from it
        // to find the result.
        var sum = 0;
        for (i = 0; i < n; i++)
            sum += arr[i];
        return sum - (((n - 1) * n) / 2);
    }
 
    // Driver code
        var arr = [ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 ];
        var n = arr.length;
        document.write(findRepeating(arr, n));
 
// This code is contributed by Rajput-Ji
</script>

Output

8

Time Complexity: O(n)
Auxiliary Space: O(1)
Causes overflow for large arrays.

Method 4 (Use Hashing): Use a hash table to store elements visited. If a seen element appears again, we return it.

C++




// CPP program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
#include <bits/stdc++.h>
using namespace std;
 
int findRepeating(int arr[], int n)
{
   unordered_set<int> s;
   for (int i=0; i<n; i++)
   {
      if (s.find(arr[i]) != s.end())
         return arr[i];
      s.insert(arr[i]);
   }
    
   // If input is correct, we should
   // never reach here
   return -1;
}
 
// driver code
int main()
{  
    int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findRepeating(arr, n);
    return 0;
}

Java




import java.util.*;
// Java program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
 
class GFG
{
 
static int findRepeating(int arr[], int n)
{
    HashSet<Integer> s = new HashSet<Integer>();
    for (int i = 0; i < n; i++)
    {
        if (s.contains(arr[i]))
            return arr[i];
        s.add(arr[i]);
    }
     
    // If input is correct, we should
    // never reach here
    return -1;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int n = arr.length;
    System.out.println(findRepeating(arr, n));;
}
}
 
// This code is contributed by Rajput-Ji

Python3




# Python3 program to find the only
# repeating element in an array
# where elements are from 1 to n-1.
def findRepeating(arr, n):
    s = set()
    for i in range(n):
        if arr[i] in s:
            return arr[i]
        s.add(arr[i])
     
    # If input is correct, we should
    # never reach here
    return -1
 
# Driver code
arr = [9, 8, 2, 6, 1, 8, 5, 3]
n = len(arr)
print(findRepeating(arr, n))
 
# This code is contributed
# by Shrikant13

C#




// C# program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
using System;
using System.Collections.Generic;
 
class GFG
{
 
static int findRepeating(int []arr, int n)
{
    HashSet<int> s = new HashSet<int>();
    for (int i = 0; i < n; i++)
    {
        if (s.Contains(arr[i]))
            return arr[i];
        s.Add(arr[i]);
    }
     
    // If input is correct, we should
    // never reach here
    return -1;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int n = arr.Length;
    Console.WriteLine(findRepeating(arr, n));;
}
}
 
// This code has been contributed by 29AjayKumar

Javascript




<script>
    
// JavaScript program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
 
function findRepeating(arr,n)
{
  s = new Set();
   for (let i = 0; i < n; i++)
   {
      if (s.has(arr[i]))
         return arr[i];
      s.add(arr[i]);
   }
    
   // If input is correct, we should
   // never reach here
   return -1;
}
 
// driver code
let arr = [ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 ];
let n = arr.length;
document.write(findRepeating(arr, n));
 
// This code is contributed by shinjanpatra.
</script>

Output

8

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

Method 5(Use XOR): The idea is based on the fact that x ^ x = 0 and x ^ y = y ^ x.
1) Compute XOR of elements from 1 to n-1.
2) Compute XOR of array elements.
3) XOR of above two would be our result.

C++




// CPP program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
#include <bits/stdc++.h>
using namespace std;
 
int findRepeating(int arr[], int n)
{
 
  // res is going to store value of
  // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^
  // arr[1] ^ .... arr[n-1]
  int res = 0;
  for (int i=0; i<n-1; i++)
    res = res ^ (i+1) ^ arr[i];
  res = res ^ arr[n-1];
  return res;
}
 
// driver code
int main()
{  
  int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
  int n = sizeof(arr) / sizeof(arr[0]);
  cout << findRepeating(arr, n);
  return 0;
}

Java




// Java program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
class GFG
{
     
    static int findRepeating(int arr[], int n)
    {
     
        // res is going to store value of
        // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^
        // arr[1] ^ .... arr[n-1]
        int res = 0;
        for (int i = 0; i < n - 1; i++)
            res = res ^ (i + 1) ^ arr[i];
        res = res ^ arr[n - 1];
             
        return res;
    }
     
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int n = arr.length;
        System.out.println(findRepeating(arr, n));
    }
}
 
// This code is contributed by
// Smitha Dinesh Semwal.

Python3




# Python3 program to find the only
# repeating element in an array where
# elements are from 1 to n-1.
 
def findRepeating(arr, n):
     
    # res is going to store value of
    # 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^
    # arr[1] ^ .... arr[n-1]
    res = 0
    for i in range(0, n-1):
        res = res ^ (i+1) ^ arr[i]
    res = res ^ arr[n-1]
         
    return res
     
# Driver code
arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
n = len(arr)
print(findRepeating(arr, n))
 
# This code is contributed by Smitha Dinesh Semwal.

C#




// C# program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
using System;
public class GFG
{
 
  static int findRepeating(int []arr, int n)
  {
 
    // res is going to store value of
    // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^
    // arr[1] ^ .... arr[n-1]
    int res = 0;
    for (int i = 0; i < n - 1; i++)
      res = res ^ (i + 1) ^ arr[i];
    res = res ^ arr[n - 1];
 
    return res;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int []arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int n = arr.Length;
    Console.WriteLine(findRepeating(arr, n));
  }
}
 
// This code is contributed by Rajput-Ji

PHP




<?php
// PHP program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
 
function findRepeating($arr, $n)
{
 
    // res is going to store value of
    // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^
    // arr[1] ^ .... arr[n-1]
    $res = 0;
    for($i = 0; $i < $n - 1; $i++)
        $res = $res ^ ($i + 1) ^ $arr[$i];
    $res = $res ^ $arr[$n - 1];
         
    return $res;
}
 
    // Driver Code
    $arr =array(9, 8, 2, 6, 1, 8, 5, 3, 4, 7);
    $n = sizeof($arr) ;
    echo findRepeating($arr, $n);
     
// This code is contributed by ajit
?>

Javascript




<script>
 
// JavaScript program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
 
 
function findRepeating(arr,n)
{
 
  // res is going to store value of
  // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^
  // arr[1] ^ .... arr[n-1]
  let res = 0;
  for (let i=0; i<n-1; i++)
    res = res ^ (i+1) ^ arr[i];
  res = res ^ arr[n-1];
  return res;
}
 
// driver code
 
let arr = [ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 ];
let n = arr.length;
document.write(findRepeating(arr, n));
 
</script>

Output

8

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

Method 6: Using indexing.
1. Iterate through the array.
2. For every index visit a[index], if it is positive change the sign of element at a[index] index, else print the element.

C++




// CPP program to find the only
// repeating element in an array
// where elements are from 1 to n-1.
#include <bits/stdc++.h>
using namespace std;
 
// Function to find repeated element
int findRepeating(int arr[], int n)
{
    int missingElement = 0;
 
    // indexing based
    for (int i = 0; i < n; i++){
 
        int element = arr[abs(arr[i])];
 
        if(element < 0){
            missingElement = arr[i];
            break;
        }
     
    arr[abs(arr[i])] = -arr[abs(arr[i])];
}
 
return abs(missingElement);
 
}
 
// driver code
int main()
{
    int arr[] = { 5, 4, 3, 9, 8,
                  9, 1, 6, 2, 5};
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << findRepeating(arr, n);
 
    return 0;
}

Java




// Java program to find the only
// repeating element in an array
// where elements are from 1 to n-1.
import java.lang.Math.*;
 
class GFG
{
    // Function to find repeated element
    static int findRepeating(int arr[], int n)
    {
        int missingElement = 0;
     
        // indexing based
        for (int i = 0; i < n; i++){
     
            int absVal = Math.abs(arr[i]);
            int element = arr[absVal];
     
            if(element < 0){
                missingElement = arr[i];
                break;
            }
         
        int absVal = Math.abs(arr[i]);
        arr[absVal] = -arr[absVal];
    }
     
    return Math.abs(missingElement);
     
    }
     
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 5, 4, 3, 9, 8,
                    9, 1, 6, 2, 5};
     
        int n = arr.length;
     
        System.out.println(findRepeating(arr, n));
     
    }
}
// This code is contributed by
// Smitha Dinesh Semwal.

Python3




# Python3 program to find the only
# repeating element in an array
# where elements are from 1 to n-1.
 
# Function to find repeated element
def findRepeating(arr, n):
 
    missingElement = 0
 
    # indexing based
    for i in range(0, n):
 
        element = arr[abs(arr[i])]
 
        if(element < 0):
            missingElement = arr[i]
            break
         
        arr[abs(arr[i])] = -arr[abs(arr[i])]
     
    return abs(missingElement)
 
# Driver code
arr = [5, 4, 3, 9, 8, 9, 1, 6, 2, 5]
n = len(arr)
print(findRepeating(arr, n))
 
# This code is contributed by Smitha Dinesh Semwal.

C#




// C# program to find the only
// repeating element in an array
// where elements are from 1 to n-1.
using System;
 
public class GFG
{
 
  // Function to find repeated element
  static int findRepeating(int[] arr, int n)
  {
    int missingElement = 0;
 
    // indexing based
    for (int i = 0; i < n; i++) {
 
            int absVal = Math.abs(arr[i]);
            int element = arr[absVal];
 
      if (element < 0) {
        missingElement = arr[i];
        break;
      }
 
      int absVal = Math.abs(arr[i]);
      arr[absVal] = -arr[absVal];
    }
 
    return Math.Abs(missingElement);
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    int[] arr = { 5, 4, 3, 9, 8, 9, 1, 6, 2, 5 };
 
    int n = arr.Length;
 
    Console.WriteLine(findRepeating(arr, n));
  }
}
 
// this code is contributed by phasing17

PHP




<?php
// PHP program to find the only
// repeating element in an array
// where elements are from 1 to n-1.
 
// Function to find repeated elements
function findRepeating($arr, $n)
{
    $missingElement = 0;
 
    // indexing based
    for ($i = 0; $i < $n; $i++)
    {
 
        $element = $arr[abs($arr[$i])];
 
        if($element < 0)
        {
            $missingElement = $arr[$i];
            break;
        }
     
    $arr[abs($arr[$i])] = -$arr[abs($arr[$i])];
}
 
return abs($missingElement);
 
}
 
// Driver Code
$arr = array (5, 4, 3, 9, 8,
              9, 1, 6, 2, 5);
 
$n = sizeof($arr);
 
echo findRepeating($arr, $n);
 
// This code is contributed by ajit
?>

Javascript




<script>
 
       // JavaScript program for the above approach;
 
       // Function to find repeated element
       function findRepeating(arr, n) {
           let missingElement = 0;
 
           // indexing based
           for (let i = 0; i < n; i++) {
 
               let absVal = Math.abs(arr[i]);
               let element = arr[absVal];
 
               if (element < 0) {
                   missingElement = arr[i];
                   break;
               }
 
               let absVal = Math.abs(arr[i]);
               arr[absVal] = -arr[absVal];
           }
 
           return Math.abs(missingElement);
 
       }
 
       // driver code
 
       let arr = [5, 4, 3, 9, 8,
           9, 1, 6, 2, 5];
 
       let n = arr.length;
 
       document.write(findRepeating(arr, n));
  // This code is contributed by Potta Lokesh
   </script>

Output

9

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

Method 7 : ( Linked-list cycle Method )

Use two pointers the fast and the slow. The fast one goes forward two steps each time, while the slow one goes only step each time. They must meet the same item when slow==fast. In fact, they meet in a circle, the duplicate number must be the entry point of the circle when visiting the array from array[0]. Next we just need to find the entry point. We use a point(we can use the fast one before) to visit form beginning with one step each time, do the same job to slow. When fast==slow, they meet at the entry point of the circle. The easy understood code is as follows.

C++




#include <bits/stdc++.h>
using namespace std;
 
int findDuplicate(vector<int>& nums)
{
    int slow = nums[0];
    int fast = nums[0];
   
    do{
       slow = nums[slow];
       fast = nums[nums[fast]];
    }while(slow!=fast);
   
    fast = nums[0];
    while(slow!=fast){
         slow = nums[slow];
         fast = nums[fast];
    }
   
    return slow;
}
int main()
{
    vector<int> v{ 1, 3, 2, 3, 4 };
    int ans = findDuplicate(v);
    cout << ans << endl;
    return 0;
}

Output

3

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!