Friday, November 15, 2024
Google search engine
HomeData Modelling & AIFind duplicate in an array in O(n) and by using O(1) extra...

Find duplicate in an array in O(n) and by using O(1) extra space

Given an array arr[] containing n + 1 integers where each integer is between 1 and n (inclusive). There is only one duplicate element, find the duplicate element in O(n) time complexity and O(1) space.

Examples : 

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

Approach: Firstly, the constraints of this problem imply that a cycle must exist. Because each number in an array arr[] is between 1 and n, it will necessarily point to an index that exists. Therefore, the list can be traversed infinitely, which implies that there is a cycle. Additionally, because 0 cannot appear as a value in an array arr[], arr[0] cannot be part of the cycle. Therefore, traversing the array in this manner from arr[0] is equivalent to traversing a cyclic linked list. The problem can be solved just like linked list cycle.

Below is the implementation of above approach: 

C++




// CPP code to find the repeated elements
// in the array where every other is present once
#include <iostream>
using namespace std;
 
// Function to find duplicate
int findDuplicate(int arr[])
{
    // Find the intersection point of the slow and fast.
    int slow = arr[0];
    int fast = arr[0];
    do {
        slow = arr[slow];
        fast = arr[arr[fast]];
    } while (slow != fast);
    // Find the "entrance" to the cycle.
    int ptr1 = arr[0];
    int ptr2 = slow;
    while (ptr1 != ptr2) {
        ptr1 = arr[ptr1];
        ptr2 = arr[ptr2];
    }
    return ptr1;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 3, 2, 1 };
    cout << findDuplicate(arr) << endl;
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta (kriSania804)


C




// C code to find the repeated elements
// in the array where every other is present once
#include <stdio.h>
 
// Function to find duplicate
int findDuplicate(int arr[])
{
    // Find the intersection point of the slow and fast.
    int slow = arr[0];
    int fast = arr[0];
    do {
        slow = arr[slow];
        fast = arr[arr[fast]];
    } while (slow != fast);
 
    // Find the "entrance" to the cycle.
    int ptr1 = arr[0];
    int ptr2 = slow;
    while (ptr1 != ptr2) {
        ptr1 = arr[ptr1];
        ptr2 = arr[ptr2];
    }
    return ptr1;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 3, 2, 1 };
    printf("%d", findDuplicate(arr));
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta (kriSania804)


Java




// Java code to find the repeated
// elements in the array where
// every other is present once
import java.util.*;
 
class GFG
{
 
// Function to find duplicate
public static int findDuplicate(int []arr)
{
    // Find the intersection
    // point of the slow and fast.
    int slow = arr[0];
    int fast = arr[0];
    do
    {
        slow = arr[slow];
        fast = arr[arr[fast]];
    } while (slow != fast);
 
    // Find the "entrance"
    // to the cycle.
    int ptr1 = arr[0];
    int ptr2 = slow;
    while (ptr1 != ptr2)
    {
        ptr1 = arr[ptr1];
        ptr2 = arr[ptr2];
    }
 
    return ptr1;
}
 
// Driver Code
public static void main(String[] args)
{
    int []arr = {1, 3, 2, 1};
 
    System.out.println("" +
               findDuplicate(arr));
 
    System.exit(0);
}
}
 
// This code is contributed
// by Harshit Saini


Python3




# Python code to find the
# repeated elements in the
# array where every other
# is present once
 
# Function to find duplicate
def findDuplicate(arr):
 
    # Find the intersection
    # point of the slow and fast.
    slow = arr[0]
    fast = arr[0]
    while True:
        slow = arr[slow]
        fast = arr[arr[fast]]
        if slow == fast:
            break
 
    # Find the "entrance"
    # to the cycle.
    ptr1 = arr[0]
    ptr2 = slow
    while ptr1 != ptr2:
        ptr1 = arr[ptr1]
        ptr2 = arr[ptr2]
         
    return ptr1
     
# Driver code
if __name__ == '__main__':
     
     
    arr = [ 1, 3, 2, 1 ]
 
    print(findDuplicate(arr))
 
 
# This code is contributed
# by Harshit Saini


C#




// C# code to find the repeated
// elements in the array where
// every other is present once
using System;
 
class GFG
{
 
// Function to find duplicate
public static int findDuplicate(int []arr)
{
    // Find the intersection
    // point of the slow and fast.
    int slow = arr[0];
    int fast = arr[0];
    do
    {
        slow = arr[slow];
        fast = arr[arr[fast]];
    } while (slow != fast);
 
    // Find the "entrance"
    // to the cycle.
    int ptr1 = arr[0];
    int ptr2 = slow;
    while (ptr1 != ptr2)
    {
        ptr1 = arr[ptr1];
        ptr2 = arr[ptr2];
    }
 
    return ptr1;
}
 
// Driver Code
public static void Main()
{
    int[] arr = {1, 3, 2, 1};
 
    Console.WriteLine("" +
            findDuplicate(arr));
 
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


Javascript




<script>
// JavaScript code to find the repeated elements
// in the array where every other is present once
 
// Function to find duplicate
function findDuplicate(arr)
{
 
    // Find the intersection point of
    // the slow and fast.
    let slow = arr[0];
    let fast = arr[0];
    do
    {
        slow = arr[slow];
        fast = arr[arr[fast]];
    } while (slow != fast);
 
    // Find the "entrance" to the cycle.
    let ptr1 = arr[0];
    let ptr2 = slow;
    while (ptr1 != ptr2)
    {
        ptr1 = arr[ptr1];
        ptr2 = arr[ptr2];
    }
    return ptr1;
}
 
// Driver code
    let arr = [ 1, 3, 2, 1 ];
    document.write(findDuplicate(arr) + "<br>");
     
// This code is contributed by Surbhi Tyagi.
</script>


PHP




<?php
// PHP code to find the repeated
// elements in the array where
// every other is present once
 
// Function to find duplicate
function findDuplicate(&$arr)
{
    $slow = $arr[0];
    $fast = $arr[0];
    do
    {
        $slow = $arr[$slow];
        $fast = $arr[$arr[$fast]];
    } while ($slow != $fast);
 
    // Find the "entrance"
    // to the cycle.
    $ptr1 = $arr[0];
    $ptr2 = $slow;
    while ($ptr1 != $ptr2)
    {
        $ptr1 = $arr[$ptr1];
        $ptr2 = $arr[$ptr2];
    }
 
    return $ptr1;
}
 
// Driver code
$arr = array(1, 3, 2, 1);
echo " " . findDuplicate($arr);
 
// This code is contributed
// by Shivi_Aggarwal
?>


Output

1









Complexity Analysis:

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

Another Approach: Using XOR Operator

In this approach we will be using XOR property that A ^ A = 0 to find the duplicate element. We will first XOR all the elements of the array with 0 and store the result in the variable “answer”. Then we will XOR all the elements from 1 to n with the value in “answer”, and returns the final value of “answer” which will be the duplicate element.

 1) Initialize an answer variable with 0
2) Iterate and XOR all the elements of array and update in answer variable
3) XOR answer with numbers 1 to n

Below is the implementation of above approach:

C++




// CPP code to find the repeated elements
// in the array where every other is present once
#include <iostream>
 
using namespace std;
 
// Function to find duplicate
int findDuplicate(int arr[] , int n)
{
    int answer=0;
      //XOR all the elements with 0
    for(int i=0; i<n; i++){
       answer=answer^arr[i];
    }
      //XOR all the elements with no from 1 to n
      // i.e   answer^0 = answer
    for(int i=1; i<n; i++){
       answer=answer^i;
    }
    return answer;
}
 
//Driver code
int main() {
    int arr[] = { 1, 3, 2, 1 };
      int n = sizeof(arr) / sizeof(arr[0]);
    cout << findDuplicate(arr,n);
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
   // Function to find duplicate
   public static int findDuplicate(int[] arr) {
        int answer = 0;
        int n = arr.length;
         
        // XOR all the elements with 0
        for (int i = 0; i < n; i++) {
            answer = answer ^ arr[i];
        }
         
        // XOR all the elements with no from 1 to n
        // i.e   answer^0 = answer
        for (int i = 1; i < n; i++) {
            answer = answer ^ i;
        }
         
        return answer;
    }
   
   
    public static void main (String[] args) {
       int[] arr = {1, 3, 2, 1};
        System.out.println(findDuplicate(arr));
    }
}


Python




def find_duplicate(arr):
    answer = 0
    n = len(arr)
 
    # XOR all the elements with 0
    for i in range(n):
        answer = answer ^ arr[i]
 
    # XOR all the elements with no from 1 to n
    # i.e   answer^0 = answer
    for i in range(1, n):
        answer = answer ^ i
 
    return answer
 
arr = [1, 3, 2, 1]
print(find_duplicate(arr))


C#




// C# code to find the repeated elements
// in the array where every other is present once
using System;
 
class GFG {
    // Function to find duplicate
    public static int findDuplicate(int[] arr) {
        int answer = 0;
        int n = arr.Length;
 
        // XOR all the elements with 0
        for (int i = 0; i < n; i++) {
            answer = answer ^ arr[i];
        }
 
        // XOR all the elements with no from 1 to n
        // i.e answer^0 = answer
        for (int i = 1; i < n; i++) {
            answer = answer ^ i;
        }
 
        return answer;
    }
 
    static void Main(string[] args) {
        int[] arr = {1, 3, 2, 1};
        Console.WriteLine(findDuplicate(arr));
    }
}


Javascript




function findDuplicate(arr) {
  let answer = 0;
  const n = arr.length;
 
  // XOR all the elements with 0
  for (let i = 0; i < n; i++) {
    answer = answer ^ arr[i];
  }
 
  // XOR all the elements with no from 1 to n
  // i.e   answer^0 = answer
  for (let i = 1; i < n; i++) {
    answer = answer ^ i;
  }
 
  return answer;
}
 
const arr = [1, 3, 2, 1];
console.log(findDuplicate(arr));


Output

1









Complexity Analysis:

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

Another Approach: Marking the visited elements

We are given positive integers from 1 to n where the size of array is n + 1, So we are going to traverse the array, based on the elements as indices and mark the visited elements as -ve. The moment we arrive at the visited element (-ve element) we are going to return the index of that element.

1. i = nums[i]
2. If its -ve then return the i-th index else
3. Mark the arr[i] as -ve. Repeat STEP 1

Below is the implementation of above approach: 

C++




#include <iostream>
#include <cmath>
#include<vector>
using namespace std;
 
int findDuplicate(vector<int>& arr) {
    int i = 0;
    while (true) {  // Traverse arr[ele] and mark the respective visited indices as -ve
        // Now if you find an ele as marked -ve then return the index
        i = abs(arr[i]);
        if (arr[i] < 0) {
            return i;
        }
        arr[i] = -1 * arr[i];  // Else keep on traversing until you find one
    }
}
 
int main() {
    vector<int> arr = {1, 2, 3, 1};
    cout << findDuplicate(arr) << endl;
 
    return 0;
}


Java




import java.util.*;
 
public class Main {
    public static int findDuplicate(List<Integer> arr) {
        int i = 0;
        while (true) {
            // Traverse arr[ele] and mark the respective visited indices as negative
            // If you find an element as marked negative, return the index
            i = Math.abs(arr.get(i));
            if (arr.get(i) < 0) {
                return i;
            }
            arr.set(i, -1 * arr.get(i)); // Otherwise, keep on traversing until you find one
        }
    }
 
    public static void main(String[] args) {
        List<Integer> arr = Arrays.asList(1, 2, 3, 1);
        System.out.println(findDuplicate(arr));
    }
}


Python




import math
def findDuplicate(arr):
    i = 0
    while True# Traverse arr[ele] and mark the respective visited indices as -ve
        # Now if you find an ele asmarked -ve then return the index
        i = int(math.fabs(arr[i]))
        if arr[i] < 0:
            return i
        arr[i] = -1 * arr[i]  # Else keep on traversing until you find one
 
 
arr = [1, 2, 3, 1]
print(findDuplicate(arr))
# This code is contributed by Swagato Chakraborty (swagatochakraborty123)


C#




using System;
using System.Collections.Generic;
 
class Program
{
    static int FindDuplicate(List<int> arr)
    {
        int i = 0;
        while (true)
        {
            // Traverse arr[ele] and mark the respective visited indices as -ve
            // Now if you find an ele as marked -ve, then return the index
            i = Math.Abs(arr[i]);
            if (arr[i] < 0)
            {
                return i;
            }
            arr[i] = -1 * arr[i]; // Else keep on traversing until you find one
        }
    }
 
    static void Main()
    {
        List<int> arr = new List<int> { 1, 2, 3, 1 };
        Console.WriteLine(FindDuplicate(arr));
    }
}
 
// This code is contributed by shivamgupta0987654321


Javascript




// JavaScript Program for the above approach
function findDuplicate(arr) {
    let i = 0;
    while (true) { // Traverse arr[ele] and mark the respective visited indices as -ve
        // Now if you find an ele as marked -ve then return the index
        i = Math.abs(arr[i]);
        if (arr[i] < 0) {
            return i;
        }
        arr[i] = -1 * arr[i]; // Else keep on traversing until you find one
    }
}
 
let arr = [1, 2, 3, 1];
console.log(findDuplicate(arr));
// This code is contributed by Kanchan Agarwal


Output

1

Complexity Analysis:

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

Another Approach: Place Element in the correct position

Keep placing elements in their correct position(equals to value) unless and until you find the element already present in its correct position. Thats how you found the duplicate element

Below is the implementation of above approach: 

Python




def findDuplicate(nums):
    while True:
        i = nums[0]
        if nums[i] != i:  # if not in correct position
            nums[0], nums[i] = nums[i], nums[0# place in correct position
        else:
            return # if in correct position return index
 
nums = [1, 3, 4, 2, 2]
print(findDuplicate(nums))
# This code is contributed by Swagato Chakraborty (swagatochakraborty123)


Output

1

Complexity Analysis:

  • Time Complexity: O(N)
  • Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments