Find duplicate in an array in O(n) and by using O(1) extra space
Last Updated :
11 Jul, 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
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem