Open In App

Only Repeating From 1 To n-1

Last Updated : 19 Apr, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given an array arr[] of size n filled with numbers from 1 to n-1 in random order. The array has only one repetitive element. The task is to find the repetitive element.

Examples:

Input: arr[] = [1, 3, 2, 3, 4]
Output: 3
Explanation: The number 3 is the only repeating element.

Input: arr[] = [1, 5, 1, 2, 3, 4]
Output: 1
Explanation: The number 1 is the only repeating element.

[Naive Approach] Using Nested Loop- O(n^2) Time and O(1) Space

The idea is to 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.

C++
// C++ program to find the 
// duplicate element
#include <iostream>
#include <vector>
using namespace std;

// Function to find the dupicate
// element in an array
int findDuplicate(vector<int>& arr) {
    int n = arr.size();

    // Find the duplicate element
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (arr[i] == arr[j])
                return arr[i];
        }
    }
    return -1; 
}

int main() {
    vector<int> arr = {1, 3, 2, 3, 4};
    cout << findDuplicate(arr);
    return 0;
}
Java
// Java program to find the 
// duplicate element
class GfG {

    // Function to find the duplicate
    // element in an array
    static int findDuplicate(int[] arr) {
        int n = arr.length;

        // Find the duplicate element
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (arr[i] == arr[j])
                    return arr[i];
            }
        }
        return -1; 
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        System.out.println(findDuplicate(arr));
    }
}
Python
# Python program to find the 
# duplicate element

# Function to find the duplicate
# element in an array
def findDuplicate(arr):
    n = len(arr)

    # Find the duplicate element
    for i in range(n):
        for j in range(i + 1, n):
            if arr[i] == arr[j]:
                return arr[i]
    return -1

if __name__ == "__main__":
    arr = [1, 3, 2, 3, 4]
    print(findDuplicate(arr))
C#
// C# program to find the 
// duplicate element
using System;

class GfG {

    // Function to find the duplicate
    // element in an array
    static int findDuplicate(int[] arr) {
        int n = arr.Length;

        // Find the duplicate element
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (arr[i] == arr[j])
                    return arr[i];
            }
        }
        return -1; 
    }

    public static void Main(string[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        Console.WriteLine(findDuplicate(arr));
    }
}
JavaScript
// JavaScript program to find the 
// duplicate element

// Function to find the duplicate
// element in an array
function findDuplicate(arr) {
    const n = arr.length;

    // Find the duplicate element
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            if (arr[i] === arr[j])
                return arr[i];
        }
    }
    return -1; 
}

// Driver code 
const arr = [1, 3, 2, 3, 4];
console.log(findDuplicate(arr));

Output
3

[Better Approach 1] Sorting - O(n Log n) Time and O(1) Space

The idea is to sort the given input array and traverse it. If value of the ith element is equal to i+1, then the current element is repetitive as value of elements is between 1 and N-1 and every element appears only once except one element.

C++
// C++ Program to find the 
// duplicate element
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int findDuplicate(vector<int>& arr) {

    // Sort the array
    sort(arr.begin(), arr.end()); 

    for (int i = 0; i < arr.size() - 1; i++) {

        // If the adjacent elements are equal
        if (arr[i] == arr[i + 1]) {
            return arr[i];
        }
    }
    return -1;
}

int main() {
    vector<int> arr = {1, 3, 2, 3, 4};
    cout << findDuplicate(arr);
    return 0;
}
Java
// Java Program to find the 
// duplicate element
import java.util.Arrays;

class GfG {

    static int findDuplicate(int[] arr) {

        // Sort the array
        Arrays.sort(arr);

        for (int i = 0; i < arr.length - 1; i++) {

            // If the adjacent elements are equal
            if (arr[i] == arr[i + 1]) {
                return arr[i];
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        System.out.println(findDuplicate(arr));
    }
}
Python
# Python Program to find the 
# duplicate element

def findDuplicate(arr):

    # Sort the array
    arr.sort()

    for i in range(len(arr) - 1):

        # If the adjacent elements are equal
        if arr[i] == arr[i + 1]:
            return arr[i]
    return -1

if __name__ == "__main__":
    arr = [1, 3, 2, 3, 4]
    print(findDuplicate(arr))
C#
// C# Program to find the 
// duplicate element
using System;

class GfG {

    static int findDuplicate(int[] arr) {

        // Sort the array
        Array.Sort(arr);

        for (int i = 0; i < arr.Length - 1; i++) {

            // If the adjacent elements are equal
            if (arr[i] == arr[i + 1]) {
                return arr[i];
            }
        }
        return -1;
    }

    public static void Main(string[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        Console.WriteLine(findDuplicate(arr));
    }
}
JavaScript
// JavaScript Program to find the 
// duplicate element

function findDuplicate(arr) {

    // Sort the array
    arr.sort((a, b) => a - b);

    for (let i = 0; i < arr.length - 1; i++) {

        // If the adjacent elements are equal
        if (arr[i] === arr[i + 1]) {
            return arr[i];
        }
    }
    return -1;
}

// Driver Code
const arr = [1, 3, 2, 3, 4];
console.log(findDuplicate(arr));

Output
3

[Better Approach 2] Hash Set - O(n) Time and O(n) Space

Use a HastSet to store elements visited. If an already visited element appears again, return it.

C++
// C++ Program to find the 
// duplicate element
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

int findDuplicate(vector<int>& arr) {

    // Create an unordered_set
    unordered_set<int> s;
    for (int x : arr) {

        // If the element is already in the set
        if (s.find(x) != s.end())
            return x;
        s.insert(x);
    }
    return -1;
}

int main() {
    vector<int> arr = {1, 3, 2, 3, 4};
    cout << findDuplicate(arr);
    return 0;
}
Java
// Java Program to find the 
// duplicate element
import java.util.HashSet;

class GfG {

    // Function to find the duplicate element
    static int findDuplicate(int[] arr) {
        
        // Create a HashSet
        HashSet<Integer> set = new HashSet<>();
        for (int x : arr) {

            // If the element is already in the set
            if (set.contains(x))
                return x;
            set.add(x);
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        System.out.println(findDuplicate(arr));
    }
}
Python
# Python Program to find the 
# duplicate element

# Function to find the duplicate element
def findDuplicate(arr):
    
    # Create a set
    s = set()
    for x in arr:

        # If the element is already in the set
        if x in s:
            return x
        s.add(x)
    return -1

if __name__ == "__main__":
    arr = [1, 3, 2, 3, 4]
    print(findDuplicate(arr))
C#
// C# Program to find the 
// duplicate element
using System;
using System.Collections.Generic;

class GfG {

    // Function to find the duplicate element
    static int FindDuplicate(int[] arr) {
        
        // Create a HashSet
        HashSet<int> set = new HashSet<int>();
        foreach (int x in arr) {

            // If the element is already in the set
            if (set.Contains(x))
                return x;
            set.Add(x);
        }
        return -1;
    }

    static void Main(string[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        Console.WriteLine(FindDuplicate(arr));
    }
}
JavaScript
// JavaScript Program to find the 
// duplicate element

// Function to find the duplicate element
function findDuplicate(arr) {
    
    // Create a Set
    let set = new Set();
    for (let x of arr) {

        // If the element is already in the set
        if (set.has(x))
            return x;
        set.add(x);
    }
    return -1;
}

// Driver function
let arr = [1, 3, 2, 3, 4];
console.log(findDuplicate(arr));

Output
3

[Expected Approach 1] Sum Formula - O(n) Time and O(1) Space

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++
// C++ program to find the 
// duplicate element
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int findDuplicate(vector<int>& arr) {
    long long n = arr.size();
  
    // Find the sum of elements in the array
    // and subtract the sum of the first n-1 
    // natural numbers to find the repeating element.
    long long  sum = accumulate(arr.begin(), arr.end(), 0);
    int duplicate = sum - ((n - 1) * n / 2);
    return duplicate;
}

int main() {
    vector<int> arr = {1, 3, 2, 3, 4};
    cout << findDuplicate(arr);
    return 0;
}
Java
// Java program to find the 
// duplicate element

class GfG {

    static int findDuplicate(int[] arr) {
        int n = arr.length;

        // Use long to avoid overflow
        long sum = 0;
        for (int num : arr) {
            sum += num;
        }

        // Expected sum of numbers from 1 to n-1
        long expectedSum = (long)(n - 1) * (n - 1 + 1) / 2;

        return (int)(sum - expectedSum);
}


    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        System.out.println(findDuplicate(arr));
    }
}
Python
# Python program to find the duplicate element

def findDuplicate(arr):
    n = len(arr)
  
    # Find the sum of elements in the array
    # and subtract the sum of the first n-1 
    # natural numbers to find the repeating element.
    totalSum = sum(arr)
    duplicate = totalSum - ((n - 1) * n // 2)
    return duplicate

if __name__ == "__main__":
    arr = [1, 3, 2, 3, 4]
    print(findDuplicate(arr))
C#
// C# program to find the 
// duplicate element
using System;

class GfG {

    static int findDuplicate(int[] arr) {
        int n = arr.Length;
  
        // Find the sum of elements in the array
        // and subtract the sum of the first n-1 
        // natural numbers to find the repeating element.
        int sum = 0;
        foreach (int num in arr) {
            sum += num;
        }
        int duplicate = sum - ((n - 1) * n / 2);
        return duplicate;
    }

    static void Main(string[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        Console.WriteLine(findDuplicate(arr));
    }
}
JavaScript
// JavaScript program to find the 
// duplicate element

function findDuplicate(arr) {
    let n = arr.length;
  
    // Find the sum of elements in the array
    // and subtract the sum of the first n-1 
    // natural numbers to find the repeating element.
    let sum = arr.reduce((acc, num) => acc + num, 0);
    let duplicate = sum - ((n - 1) * n / 2);
    return duplicate;
}

// Driver code 
let arr = [1, 3, 2, 3, 4];
console.log(findDuplicate(arr));

Output
3

[Expected Approach 2] Using XOR - O(n) Time and O(1) Space

The idea is based on the facts that x ^ x = 0 and if x ^ y = z then x ^ z = y. To find the duplicate element first find XOR of elements from 1 to n-1 and elements of array. XOR of these two would be our result.

C++
// C++ program to find the 
// duplicate element
#include <iostream>
#include <vector>
using namespace std;

// Function to find the dupicate
// element in an array
int findDuplicate(vector<int>& arr) {
    int n = arr.size();
    int res = 0;

    // XOR all numbers from 1 to n-1 and 
    // elements in the array
    for (int i = 0; i < n - 1; i++) {
        res = res ^ (i + 1) ^ arr[i];
    }
    
    // XOR the last element in the array
    res = res ^ arr[n - 1];
    
    return res;
}

int main() {
    vector<int> arr = {1, 3, 2, 3, 4};
    cout << findDuplicate(arr);
    return 0;
}
Java
// Java program to find the 
// duplicate element

class GfG {

    // Function to find the duplicate
    // element in an array
    static int findDuplicate(int[] arr) {
        int n = arr.length;
        int res = 0;

        // XOR all numbers from 1 to n-1 and 
        // elements in the array
        for (int i = 0; i < n - 1; i++) {
            res = res ^ (i + 1) ^ arr[i];
        }
        
        // XOR the last element in the array
        res = res ^ arr[n - 1];
        
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        System.out.println(findDuplicate(arr));
    }
}
Python
# Python program to find the 
# duplicate element

# Function to find the duplicate
# element in an array
def findDuplicate(arr):
    n = len(arr)
    res = 0

    # XOR all numbers from 1 to n-1 and 
    # elements in the array
    for i in range(n - 1):
        res = res ^ (i + 1) ^ arr[i]
    
    # XOR the last element in the array
    res = res ^ arr[n - 1]
    
    return res

if __name__ == "__main__":
    arr = [1, 3, 2, 3, 4]
    print(findDuplicate(arr))
C#
// C# program to find the 
// duplicate element
using System;

class GfG {

    // Function to find the duplicate
    // element in an array
    static int findDuplicate(int[] arr) {
        int n = arr.Length;
        int res = 0;

        // XOR all numbers from 1 to n-1 and 
        // elements in the array
        for (int i = 0; i < n - 1; i++) {
            res = res ^ (i + 1) ^ arr[i];
        }
        
        // XOR the last element in the array
        res = res ^ arr[n - 1];
        
        return res;
    }

    static void Main(string[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        Console.WriteLine(findDuplicate(arr));
    }
}
JavaScript
// JavaScript program to find the 
// duplicate element

// Function to find the duplicate
// element in an array
function findDuplicate(arr) {
    let n = arr.length;
    let res = 0;

    // XOR all numbers from 1 to n-1 and 
    // elements in the array
    for (let i = 0; i < n - 1; i++) {
        res = res ^ (i + 1) ^ arr[i];
    }
    
    // XOR the last element in the array
    res = res ^ arr[n - 1];
    
    return res;
}

// Driver code 
let arr = [1, 3, 2, 3, 4];
console.log(findDuplicate(arr));

Output
3

[Expected Approach 3] Using Elements as Indexes - O(n) Time and O(1) Space

As there are only positive numbers, so visit the index equal to the current element and make it negative. If an index value is already negative, then it means that current element is repeated.

C++
#include <iostream>
#include <vector>
using namespace std;

// Function to find the dupicate
// element in an array
int findDuplicate(vector<int>& arr) {

    for (int i = 0; i < arr.size(); i++) {
        if (arr[abs(arr[i])] < 0) {
            return abs(arr[i]);
        }
        arr[abs(arr[i])] = -arr[abs(arr[i])];
    }

    return -1;
}

int main() {
    vector<int> arr = {1, 3, 2, 3, 4};
    cout << findDuplicate(arr);
    return 0;
}
Java
class GfG {

    // Function to find the duplicate
    // element in an array
    static int findDuplicate(int[] arr) {

        for (int i = 0; i < arr.length; i++) {
            if (arr[Math.abs(arr[i])] < 0) {
                return Math.abs(arr[i]);
            }
            arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        System.out.println(findDuplicate(arr));
    }
}
Python
# Function to find the duplicate
# element in an array
def findDuplicate(arr):
    for i in range(len(arr)):
        if arr[abs(arr[i])] < 0:
            return abs(arr[i])
        arr[abs(arr[i])] = -arr[abs(arr[i])]
    return -1
    
if __name__ == "__main__":
    arr = [1, 3, 2, 3, 4]
    print(findDuplicate(arr))
C#
using System;

class GfG {

    // Function to find the duplicate
    // element in an array
    static int findDuplicate(int[] arr) {

        for (int i = 0; i < arr.Length; i++) {
            if (arr[Math.Abs(arr[i])] < 0) {
                return Math.Abs(arr[i]);
            }
            arr[Math.Abs(arr[i])] = -arr[Math.Abs(arr[i])];
        }

        return -1;
    }

    static void Main(string[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        Console.WriteLine(findDuplicate(arr));
    }
}
JavaScript
// Function to find the duplicate
// element in an array
function findDuplicate(arr) {

    for (let i = 0; i < arr.length; i++) {
        if (arr[Math.abs(arr[i])] < 0) {
            return Math.abs(arr[i]);
        }
        arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
    }

    return -1;
}

// Driver Code 
let arr = [1, 3, 2, 3, 4];
console.log(findDuplicate(arr));

Output
3

[Expected Approach 4] Floyd's Cycle Detection - O(n) Time and O(1) Space

Floyd's Cycle Detection Algorithm is used to detect whether the list or array has cycle or duplicate elements or not. In this approach, there are 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 and they 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 from the beginning with one step each time, do the same job to slow. When fast == slow, they meet at the entry point of the circle. 

Note: Please refer remove loop from a linked list for proof of this method

C++
// C++ program to find the 
// duplicate element
#include <iostream>
#include <vector>
using namespace std;

// Function to find the dupicate
// element in an array
int findDuplicate(vector<int>& arr) {

    // slow pointer
    int slow = arr[0]; 

    // fast pointer
    int fast = arr[0]; 

    do {

        // moves one step
        slow = arr[slow];  

        // moves two steps
        fast = arr[arr[fast]];     
    } while (slow != fast);

    // reinitialize fast to the start
    fast = arr[0]; 
  
    // Loop until both pointers meet at the duplicate
    while (slow != fast) {
        slow = arr[slow];
        fast = arr[fast];
    }
  
   // Return duplicate number
    return slow;
}

int main() {
    vector<int> arr = {1, 3, 2, 3, 4};
    cout << findDuplicate(arr);
    return 0;
}
Java
// Java program to find the 
// duplicate element

class GfG {

    // Function to find the duplicate
    // element in an array
    static int findDuplicate(int[] arr) {

        // slow pointer
        int slow = arr[0]; 

        // fast pointer
        int fast = arr[0]; 

        do {

            // moves one step
            slow = arr[slow];  

            // moves two steps
            fast = arr[arr[fast]];     
        } while (slow != fast);

        // reinitialize fast to the start
        fast = arr[0]; 
  
        // Loop until both pointers meet at the duplicate
        while (slow != fast) {
            slow = arr[slow];
            fast = arr[fast];
        }
  
       // Return duplicate number
        return slow;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        System.out.println(findDuplicate(arr));
    }
}
Python
# Python program to find the 
# duplicate element

# Function to find the duplicate
# element in an array
def findDuplicate(arr):

    # slow pointer
    slow = arr[0] 

    # fast pointer
    fast = arr[0] 

    while True:

        # moves one step
        slow = arr[slow]  

        # moves two steps
        fast = arr[arr[fast]]     
        if slow == fast:
            break

    # reinitialize fast to the start
    fast = arr[0] 
  
    # Loop until both pointers meet at the duplicate
    while slow != fast:
        slow = arr[slow]
        fast = arr[fast]
  
    # Return duplicate number
    return slow
    
if __name__ == "__main__":
    arr = [1, 3, 2, 3, 4]
    print(findDuplicate(arr))
C#
// C# program to find the 
// duplicate element
using System;

class GfG {

    // Function to find the duplicate
    // element in an array
    static int findDuplicate(int[] arr) {

        // slow pointer
        int slow = arr[0]; 

        // fast pointer
        int fast = arr[0]; 

        do {

            // moves one step
            slow = arr[slow];  

            // moves two steps
            fast = arr[arr[fast]];     
        } while (slow != fast);

        // reinitialize fast to the start
        fast = arr[0]; 
  
        // Loop until both pointers meet at the duplicate
        while (slow != fast) {
            slow = arr[slow];
            fast = arr[fast];
        }
  
       // Return duplicate number
        return slow;
    }

    static void Main(string[] args) {
        int[] arr = {1, 3, 2, 3, 4};
        Console.WriteLine(findDuplicate(arr));
    }
}
JavaScript
// JavaScript program to find the 
// duplicate element

// Function to find the duplicate
// element in an array
function findDuplicate(arr) {

    // slow pointer
    let slow = arr[0]; 

    // fast pointer
    let fast = arr[0]; 

    do {

        // moves one step
        slow = arr[slow];  

        // moves two steps
        fast = arr[arr[fast]];     
    } while (slow !== fast);

    // reinitialize fast to the start
    fast = arr[0]; 
  
    // Loop until both pointers meet at the duplicate
    while (slow !== fast) {
        slow = arr[slow];
        fast = arr[fast];
    }
  
   // Return duplicate number
    return slow;
}

// Driver Code
let arr = [1, 3, 2, 3, 4];
console.log(findDuplicate(arr));

Output
3

Next Article

Similar Reads