The Wayback Machine - https://web.archive.org/web/20250114041508/https://www.geeksforgeeks.org/find-repetitive-element-1-n-1/
Open In App

Only Repeating From 1 To n-1

Last Updated : 06 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array 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: a[] = {1, 3, 2, 3, 4}
Output: 3
Explanation: The number 3 is the only repeating element.

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

Naive Approach – O(n^2) Time and O(1) Space

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++
#include <iostream>
#include <vector>
using namespace std;

int findRepeating(const vector<int>& arr)
{
    int n = arr.size();
    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 = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };

    // Function call
    cout << findRepeating(arr);
    return 0;
}
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;
    }

    static public void main(String[] args)
    {
        int[] arr
            = new int[] { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int repeatingNum = findRepeating(arr);
        System.out.println(repeatingNum);
    }
}
Python
def find_repeating(arr):
    n = len(arr)
    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 = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
    print(find_repeating(arr))
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;
    }

    static public void Main()
    {
        int[] arr
            = new int[] { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int repeatingNum = findRepeating(arr);
        Console.WriteLine(repeatingNum);
    }
}
JavaScript
// Function to find the first repeating element
function findRepeating(arr) {
    const n = arr.length;
    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;
}

// Main function
const arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7];
console.log(findRepeating(arr));

Output
8

Better Approach – Sorting – O(n Log n) Time and O(1) Space

Sort the given input array. Traverse the array and if value of the ith element is not 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++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int findRepeating(vector<int>& arr)
{
    sort(arr.begin(), arr.end()); 

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

int main()
{
    vector<int> arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    cout << findRepeating(arr);
    return 0;
}
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's code
    static public void main(String[] args)
    {
        int[] arr
            = new int[] { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int N = arr.length;
      
          // Function call
        int repeatingNum = findRepeating(arr, N);
        System.out.println(repeatingNum);
    }
}

// This code is contributed by Abhijeet Kumar(abhijeet19403)
Python
# 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):
        if(arr[i] != i+1):
            return arr[i]


# Driver's Code
if __name__ == "__main__":
  arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
  N = len(arr)

  # Function call
  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;
    }

      // Driver's code
    static public void Main()
    {
        int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int N = arr.Length;
      
          // Function call
        int repeatingNum = findRepeating(arr, N);
        Console.WriteLine(repeatingNum);
    }
}

// This code is contributed by lokesh (lokeshmvs21).
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){
    arr.sort();
    for (let i = 0; i < N; i++) {
          
    // compare array element with its index
        if (arr[i] != i + 1) {
              return arr[i];
            }
        }
        return -1;
}
           // Driver code
let arr= [ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 ];
let N = arr.length;

// Function call
console.log(findRepeating(arr, N));
     
// This code is contributed by aarohirai2616.
</script>

Output
8

Expected Approach 1 – Hash Set – O(n) Time and O(n) Space

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

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

int findRepeating(vector<int>& arr)
{
    unordered_set<int> s;
    for (int x : arr) {
        if (s.find(x) != s.end())
            return x;
        s.insert(x);
    }
    return -1;
}

int main()
{
    vector<int> arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    cout << findRepeating(arr);
    return 0;
}
Java
// Java implementation
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static int findRepeating(int[] arr) {
        Set<Integer> s = new HashSet<>();
        for (int x : arr) {
            if (s.contains(x))
                return x;
            s.add(x);
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        System.out.println(findRepeating(arr));
    }
}
Python
# Python implementation
def find_repeating(arr):
    s = set()
    for x in arr:
        if x in s:
            return x
        s.add(x)
    return -1

arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
print(find_repeating(arr))
C#
// Function to find the first repeating element
using System;
using System.Collections.Generic;

class Program
{
    static int FindRepeating(int[] arr)
    {
        HashSet<int> s = new HashSet<int>();
        foreach (int x in arr)
        {
            if (s.Contains(x))
                return x;
            s.Add(x);
        }
        return -1;
    }

    static void Main()
    {
        int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        Console.WriteLine(FindRepeating(arr));
    }
}
JavaScript
// Function to find the first repeating element
function findRepeating(arr) {
    const s = new Set();
    for (let x of arr) {
        if (s.has(x))
            return x;
        s.add(x);
    }
    return -1;
}

// Main function
const arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7];
console.log(findRepeating(arr));

Output
8

Expected Approach 2 – Visited Array – O(n) Time and O(n) Space

Use an array to keep track of the visited elements in array. If an already visited element is seen again, then it is the repeating element.

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

int findRepeating(vector<int>& arr)
{
    int n = arr.size();
  
    // If any element is visited again, then
    // it is the repeating element
    vector<bool> visited(n + 1, 0); 
    for (int i = 0; i < n; i++) {
        if (visited[arr[i]])
            return arr[i];
        visited[arr[i]] = true;
    }

    return -1; 
}

int main()
{
    vector<int> arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    cout << findRepeating(arr);
    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>

int findRepeating(int arr[], int n) {
  
    // If any element is visited again, then
    // it is the repeating element
    bool visited[n + 1];
    for (int i = 0; i <= n; i++) {
        visited[i] = false;
    }
  
    for (int i = 0; i < n; i++) {
        if (visited[arr[i]])
            return arr[i];
        visited[arr[i]] = true;
    }
    return -1;
}

int main() {
    int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d", findRepeating(arr, n));
    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static int findRepeating(List<Integer> arr) {
        int n = arr.size();

        // If any element is visited again, then
        // it is the repeating element
        boolean[] visited = new boolean[n + 1];
        for (int i = 0; i < n; i++) {
            if (visited[arr.get(i)])
                return arr.get(i);
            visited[arr.get(i)] = true;
        }

        return -1;
    }

    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        arr.add(9);
        arr.add(8);
        arr.add(2);
        arr.add(6);
        arr.add(1);
        arr.add(8);
        arr.add(5);
        arr.add(3);
        arr.add(4);
        arr.add(7);
        System.out.println(findRepeating(arr));
    }
}
Python
def find_repeating(arr):
    n = len(arr)
    
    # If any element is visited again, then
    # it is the repeating element
    visited = [False] * (n + 1)
    for i in range(n):
        if visited[arr[i]]:
            return arr[i]
        visited[arr[i]] = True

    return -1

arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
print(find_repeating(arr))
C#
using System;
using System.Collections.Generic;

class Program
{
    static int FindRepeating(List<int> arr)
    {
        int n = arr.Count;
      
        // If any element is visited again, then
        // it is the repeating element
        bool[] visited = new bool[n + 1];
        for (int i = 0; i < n; i++)
        {
            if (visited[arr[i]])
                return arr[i];
            visited[arr[i]] = true;
        }
        return -1;
    }

    static void Main()
    {
        List<int> arr = new List<int> { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        Console.WriteLine(FindRepeating(arr));
    }
}
JavaScript
function findRepeating(arr) {
    const n = arr.length;
    
    // If any element is visited again, then
    // it is the repeating element
    const visited = new Array(n + 1).fill(false);
    for (let i = 0; i < n; i++) {
        if (visited[arr[i]])
            return arr[i];
        visited[arr[i]] = true;
    }
    return -1;
}

const arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7];
console.log(findRepeating(arr));

Output
8

Sum Formula – O(n) Time and O(1) Space – Might Cause Overflow

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++
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int findRepeating(vector<int>& arr)
{
    int 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.
    return accumulate(arr.begin(), arr.end(), 0) - ((n - 1) * n / 2);
}

int main()
{
    vector<int> arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    cout << findRepeating(arr);
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

int findRepeating(int arr[], int n) {
  
    // 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;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
    return sum - ((n - 1) * n / 2);
}

int main() {
    int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", findRepeating(arr, n));
    return 0;
}
Java
import java.util.Arrays;
import java.util.stream.IntStream;

public class Main {
    public static int findRepeating(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.
        return IntStream.of(arr).sum() - (n - 1) * n / 2;
    }

    public static void main(String[] args) {
        int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        System.out.println(findRepeating(arr));
    }
}
Python
def find_repeating(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.
    return sum(arr) - (n - 1) * n // 2

arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
print(find_repeating(arr))
C#
// Function to find the repeating element in an array
using System;
using System.Linq;

class Program
{
    static int FindRepeating(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.
        return arr.Sum() - ((n - 1) * n / 2);
    }

    static void Main()
    {
        int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        Console.WriteLine(FindRepeating(arr));
    }
}
JavaScript
// Function to find the repeating element in an array
function findRepeating(arr) {
    const 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.
    return arr.reduce((a, b) => a + b, 0) - ((n - 1) * n / 2);
}

const arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7];
console.log(findRepeating(arr));

Output
8

Expected Approach 3 – 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

Follow the below steps to solve the problem:

  • Compute XOR of elements from 1 to n-1.
  • Compute XOR of array elements.
  • XOR of the above two would be our result.

Below is the implementation of the above approach:

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

int findRepeating(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 = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    cout << findRepeating(arr);
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

int findRepeating(int arr[], int n) {
    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 ^= (i + 1) ^ arr[i];
    }
    
    // XOR the last element in the array
    res ^= arr[n - 1];
    
    return res;
}

int main() {
    int arr[] = {9, 8, 2, 6, 1, 8, 5, 3, 4, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", findRepeating(arr, n));
    return 0;
}
Java
import java.util.Arrays;
import java.util.List;

public class GfG {
    public static int findRepeating(List<Integer> 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.get(i);
        }
        
        // XOR the last element in the array
        res = res ^ arr.get(n - 1);
        
        return res;
    }

    public static void main(String[] args) {
        List<Integer> arr = Arrays.asList(9, 8, 2, 6, 1, 8, 5, 3, 4, 7);
        System.out.println(findRepeating(arr));
    }
}
Python
def find_repeating(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 ^= (i + 1) ^ arr[i]
    
    # XOR the last element in the array
    res ^= arr[n - 1]
    
    return res

arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
print(find_repeating(arr))
JavaScript
function findRepeating(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 ^= (i + 1) ^ arr[i];
    }
    
    // XOR the last element in the array
    res ^= arr[n - 1];
    
    return res;
}

const arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7];
console.log(findRepeating(arr));

Output
8

Expected Approach 4 – 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;

int findRepeating(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 = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    cout << findRepeating(arr) << endl;
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

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

int main() {
    int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int size = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", findRepeating(arr, size));
    return 0;
}
Java
import java.util.*;

public class GfG {
    public static int findRepeating(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 = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        System.out.println(findRepeating(arr));
    }
}
Python
def find_repeating(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 = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
    print(find_repeating(arr))
C#
using System;
using System.Collections.Generic;

class Program {
    static int FindRepeating(List<int> arr) {
        for (int i = 0; i < arr.Count; 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() {
        List<int> arr = new List<int> { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        Console.WriteLine(FindRepeating(arr));
    }
}
JavaScript
function findRepeating(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;
}

const arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7];
console.log(findRepeating(arr));

Output
8

Expected Approach 5 – Floyd’s Cycle Detection – O(n) Time and O(1) Space

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 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. 

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

C++
#include <bits/stdc++.h>
using namespace std;

int findDuplicate(vector<int>& arr)
{
    int slow = arr[0]; // slow pointer
    int fast = arr[0]; // fast pointer

    do {
        slow = arr[slow];          // moves one step (speed x)
        fast = arr[arr[fast]];     // moves two steps (speed 2x)
    } while (slow != fast);

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

// Driver code
int main()
{
    vector<int> arr{ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int res = findDuplicate(arr);
    cout << res << endl;
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

int findDuplicate(int* arr, int size) {
    int slow = arr[0]; // slow pointer
    int fast = arr[0]; // fast pointer

    do {
        slow = arr[slow];          // moves one step (speed x)
        fast = arr[arr[fast]];     // moves two steps (speed 2x)
    } while (slow != fast);

    fast = arr[0]; // reinitialize fast to the start

    // Loop until both pointers meet at the duplicate
    while (slow != fast) {
        slow = arr[slow];
        fast = arr[fast];
    }

   // Return duplicate number
    return slow;
}

// Driver code
int main() {
    int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
    int size = sizeof(arr) / sizeof(arr[0]);
    int res = findDuplicate(arr, size);
    printf("%d\n", res);
    return 0;
}
Java
import java.util.Arrays;

public class Main {
    public static int findDuplicate(int[] arr) {
        int slow = arr[0]; // slow pointer
        int fast = arr[0]; // fast pointer

        do {
            slow = arr[slow];          // moves one step (speed x)
            fast = arr[arr[fast]];     // moves two steps (speed 2x)
        } while (slow != fast);

        fast = arr[0]; // reinitialize fast to the start

        // 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 = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int res = findDuplicate(arr);
        System.out.println(res);
    }
}
Python
def findDuplicate(arr):
    slow = arr[0]  # slow pointer
    fast = arr[0]  # fast pointer

    while True:
        slow = arr[slow]          # moves one step (speed x)
        fast = arr[arr[fast]]     # moves two steps (speed 2x)
        if slow == fast:
            break

    fast = arr[0]  # reinitialize fast to the start

    # Loop until both pointers meet at the duplicate
    while slow != fast:
        slow = arr[slow]
        fast = arr[fast]

    # Return duplicate number
    return slow

# Driver code
arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]
res = findDuplicate(arr)
print(res)
C#
using System;
using System.Linq;

class Program {
    public static int FindDuplicate(int[] arr) {
        int slow = arr[0]; // slow pointer
        int fast = arr[0]; // fast pointer

        do {
            slow = arr[slow];          // moves one step (speed x)
            fast = arr[arr[fast]];     // moves two steps (speed 2x)
        } while (slow != fast);

        fast = arr[0]; // reinitialize fast to the start

        // 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() {
        int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
        int res = FindDuplicate(arr);
        Console.WriteLine(res);
    }
}
JavaScript
function findDuplicate(arr) {
    let slow = arr[0]; // slow pointer
    let fast = arr[0]; // fast pointer

    do {
        slow = arr[slow];          // moves one step (speed x)
        fast = arr[arr[fast]];     // moves two steps (speed 2x)
    } while (slow !== fast);

    fast = arr[0]; // reinitialize fast to the start

    // Loop until both pointers meet at the duplicate
    while (slow !== fast) {
        slow = arr[slow];
        fast = arr[fast];
    }

   // Return duplicate number
    return slow;
}

// Driver code
const arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7];
const res = findDuplicate(arr);
console.log(res);

Output
8

Unlock your potential with our DSA Self-Paced course, designed to help you master Data Structures and Algorithms at your own pace. In 90 days, you’ll learn the core concepts of DSA, tackle real-world problems, and boost your problem-solving skills, all at a speed that fits your schedule. With comprehensive lessons and practical exercises, this course will set you up for success in technical interviews and beyond.

And here's the challenge – join the Three 90 Challenge! Complete 90% of the course in 90 days, and you’ll earn a 90% refund. It's a great way to stay motivated, track your progress, and reward yourself for your dedication. Start the challenge today, and push your limits to achieve mastery in DSA!


Next Article

Similar Reads

three90RightbarBannerImg