Skip to content
Related Articles

Related Articles

Find duplicates in constant array with elements 0 to N-1 in O(1) space

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 14 Sep, 2022
View Discussion
Improve Article
Save Article

Given a constant array of n elements which contains elements from 1 to n-1, with any of these numbers appearing any number of times. Find any one of these repeating numbers in O(n) and using only constant memory space.

Examples: 

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

As the given array is constant methods given in below articles will not work. 

  1. Find duplicates in O(n) time and O(1) extra space | Set 1
  2. Duplicates in an array in O(n) and by using O(1) extra space | Set-2
  1. We are taking two variables i & j starting from 0
  2. We will run loop until i reached last elem or found repeated elem
  3. We will pre-increment the j value so that we can compare elem with next elem
  4. If we don’t find elem, we will increase i as j will be pointing last elem and then reposition j with  

Implementation:

Java




// Java program to find a duplicate
// element in an array with values in
// range from 0 to n-1.
import java.io.*;
import java.util.*;
 
public class GFG {
     
    // function to find one duplicate
    static int findduplicate(int []a, int n)
    {
         
        int i=0,j=0;
        while(i<n){
            if(a[i]==a[++j]) return a[j];
            if(j==n-1) {
                i++;
                j=i;
            }
        }
        return -1;
    }
     
    public static void main(String args[])
    {
        int []arr = {1, 2, 4, 3, 4, 5, 6, 3};
        int n = arr.length;
        System.out.print(findduplicate(arr, n));
    }
}
 
// This code is contributed by
// Love Raj

Java




// Java program to find a duplicate
// element in an array with values in
// range from 0 to n-1.
import java.io.*;
import java.util.*;
 
public class GFG {
      
    // function to find one duplicate
    static int findduplicate(int []arr, int n)
    {
          
        // return -1 because in these cases
        // there can not be any repeated element
        if (n <= 1)
            return -1;
      
        // initialize fast and slow
        int slow = arr[0];
        int fast = arr[arr[0]];
      
        // loop to enter in the cycle
        while (fast != slow)
        {
      
            // move one step for slow
            slow = arr[slow];
      
            // move two step for fast
            fast = arr[arr[fast]];
        }
      
        // loop to find entry
        // point of the cycle
        fast = 0;
        while (slow != fast)
        {
            slow = arr[slow];
            fast = arr[fast];
        }
        return slow;
    }
      
    // Driver Code
    public static void main(String args[])
    {
        int []arr = {1, 2, 3, 4, 5, 6, 3};
        int n = arr.length;
        System.out.print(findduplicate(arr, n));
    }
}
  
// This code is contributed by
// Manish Shaw (manishshaw1)

Python 3




# Python 3 program to find a duplicate
# element in an array with values in
# range from 0 to n-1.
 
# function to find one duplicate
def findduplicate(arr, n):
 
    # return -1 because in these cases
    # there can not be any repeated element
    if (n <= 1):
        return -1
 
    # initialize fast and slow
    slow = arr[0]
    fast = arr[arr[0]]
 
    # loop to enter in the cycle
    while (fast != slow) :
 
        # move one step for slow
        slow = arr[slow]
 
        # move two step for fast
        fast = arr[arr[fast]]
 
    # loop to find entry point of the cycle
    fast = 0
    while (slow != fast):
        slow = arr[slow]
        fast = arr[fast]
    return slow
 
# Driver Code
if __name__ == "__main__":
     
    arr = [1, 2, 3, 4, 5, 6, 3 ]
    n = len(arr)
    print(findduplicate(arr, n))
 
# This code is contributed by ita_c

C#




// C# program to find a duplicate
// element in an array with values in
// range from 0 to n-1.
using System;
using System.Collections.Generic;
class GFG {
     
    // function to find one duplicate
    static int findduplicate(int []arr, int n)
    {
         
        // return -1 because in these cases
        // there can not be any repeated element
        if (n <= 1)
            return -1;
     
        // initialize fast and slow
        int slow = arr[0];
        int fast = arr[arr[0]];
     
        // loop to enter in the cycle
        while (fast != slow)
        {
     
            // move one step for slow
            slow = arr[slow];
     
            // move two step for fast
            fast = arr[arr[fast]];
        }
     
        // loop to find entry
        // point of the cycle
        fast = 0;
        while (slow != fast)
        {
            slow = arr[slow];
            fast = arr[fast];
        }
        return slow;
    }
     
    // Driver Code
    public static void Main()
    {
        int []arr = {1, 2, 3, 4, 5, 6, 3};
        int n = arr.Length;
        Console.Write(findduplicate(arr, n));
    }
}
 
// This code is contributed by
// Manish Shaw (manishshaw1)

PHP




<?php
// PHP program to find a duplicate
// element in an array with values in
// range from 0 to n-1.
 
// function to find one duplicate
function findduplicate($arr, $n)
{
    // return -1 because in these cases
    // there can not be any repeated element
    if ($n <= 1)
        return -1;
 
    // initialize fast and slow
    $slow = $arr[0];
    $fast = $arr[$arr[0]];
 
    // loop to enter in the cycle
    while ($fast != $slow)
    {
 
        // move one step for slow
        $slow = $arr[$slow];
 
        // move two step for fast
        $fast = $arr[$arr[$fast]];
    }
 
    // loop to find entry point of the cycle
    $fast = 0;
    while ($slow != $fast)
    {
        $slow = $arr[$slow];
        $fast = $arr[$fast];
    }
    return $slow;
}
 
// Driver Code
$arr = array( 1, 2, 3, 4, 5, 6, 3 );
$n = sizeof($arr);
echo findduplicate($arr, $n);
 
// This code is contributed by Tushil
?>

Javascript




<script>
 
    // Javascript program to find a duplicate
    // element in an array with values in
    // range from 0 to n-1.
     
    // function to find one duplicate
    function findduplicate(arr, n)
    {
           
        // return -1 because in these cases
        // there can not be any repeated element
        if (n <= 1)
            return -1;
       
        // initialize fast and slow
        let slow = arr[0];
        let fast = arr[arr[0]];
       
        // loop to enter in the cycle
        while (fast != slow)
        {
       
            // move one step for slow
            slow = arr[slow];
       
            // move two step for fast
            fast = arr[arr[fast]];
        }
       
        // loop to find entry
        // point of the cycle
        fast = 0;
        while (slow != fast)
        {
            slow = arr[slow];
            fast = arr[fast];
        }
        return slow;
    }
     
    let arr = [1, 2, 3, 4, 5, 6, 3];
    let n = arr.length;
    document.write(findduplicate(arr, n));
     
</script>

Output

4

Complexity Analysis:

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

Efficient Approach:

We will use the concept that all elements here are between 1 and n-1.

So we will perform these steps to find the Duplicate element

  1.  Consider a pointer ‘p’ which is currently at index 0.
  2.  Run a while loop until the pointer p reaches the value n.
  3.  if the value of a[p] is -1 then increment the pointer by 1 and skip the iteration 
  4.  Else,go to the position of the element to which the current pointer is pointing i.e. at index a[p].
  5.  Now if the value at index a[p] i.e. a[a[p]] is -1 then break the loop as the element a[p] is the duplicate one.
  6. Otherwise store the value of a[a[p]] in a[p] i.e. a[p]=a[a[p]] and put -1 in a[a[p]] i.e. a[a[p]]=-1.

Code:       

C++




#include <iostream>
using namespace std;
 
void find_duplicate(int a[], int n)
{
    int p = 0;
    while (p != n) {
        if (a[p] == -1) {
            p++;
        }
        else {
            if (a[a[p] - 1] == -1) {
                cout << a[p] << endl;
                break;
            }
            else {
                a[p] = a[a[p] - 1];
                a[a[p] - 1] = -1;
            }
        }
    }
}
 
int main()
{
    int a[] = { 1, 2, 4, 3, 4, 5, 6, 3 };
    int n = sizeof(a) / sizeof(a[0]);
    find_duplicate(a, n);
    return 0;
}
 
// This Code is Contributed by Abhishek Purohit

Java




// Java Program for the above approach
 
import java.io.*;
 
class GFG {
 
    static void find_duplicate(int a[], int n)
    {
        int p = 0;
        while (p != n) {
            if (a[p] == -1) {
                p++;
            }
            else {
                if (a[a[p] - 1] == -1) {
                    System.out.println(a[p]);
                    break;
                }
                else {
                    a[p] = a[a[p] - 1];
                    a[a[p] - 1] = -1;
                }
            }
        }
    }
 
    public static void main(String[] args)
    {
        int[] a = { 1, 2, 4, 3, 4, 5, 6, 3 };
        int n = a.length;
 
        find_duplicate(a, n);
    }
}
 
// This Code is Contributed by lokesh (lokeshmvs21).

Output

3

Complexity Analysis:

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!