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

Last Updated : 13 Apr, 2024

Given an array arr[] containing n integers where each integer is between 1 and (n-1) (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 : 4Input  : 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 else3. 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:

C++ ```#include <iostream> void swap(int nums[], int i, int j) { // Swap the elements at indices i and j int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } int findDuplicate(int nums[]) { while (true) { int i = nums[0]; // if not in the correct position if (nums[i] != i) { swap(nums, 0, i); } else { return i; } } } int main() { int nums[] = {1, 2, 3, 1}; std::cout << findDuplicate(nums) << std::endl; return 0; } // This code is contributed by shivamgupta310570 ``` Java ```/*package whatever //do not write package name here */ import java.io.*; class GFG { public static int findDuplicate(int[] nums) { while (true) { int i = nums[0]; // if not in correct position if (nums[i] != i) { swap(nums, 0, i); } else { return i; } } } private static void swap(int[] nums, int i, int j) { // Swap the elements at indices i and j int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } public static void main(String[] args) { int[] nums = { 1, 2, 3, 1 }; System.out.println(findDuplicate(nums)); } } //This code is contributed by Rohit Singh ``` 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 i # if in correct position return index nums = [1, 3, 4, 2, 2] print(findDuplicate(nums)) # This code is contributed by Swagato Chakraborty (swagatochakraborty123) ``` C# ```// C# program for the above approach using System; public class GFG { static void Swap(int[] nums, int i, int j) { // Swap the elements at indices i and j int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } static int FindDuplicate(int[] nums) { while (true) { int i = nums[0]; // If not in the correct position if (nums[i] != i) { Swap(nums, 0, i); } else { return i; } } } static void Main() { int[] nums = { 1, 2, 3, 1 }; Console.WriteLine(FindDuplicate(nums)); } } // This code is contributed by Susobhan Akhuli ``` Javascript ```function findDuplicate(nums) { while (true) { let 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 i; // If in correct position, return index } } } let nums = [1, 3, 4, 2, 2]; console.log(findDuplicate(nums)); ```

Output

`1`

Complexity Analysis:

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

Previous
Next