Find duplicate in an array in O(n) and by using O(1) extra space
Last Updated :
02 May, 2025
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 : 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
Python
# 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
?>
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));
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:
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)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read