Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space.
Example:
Input : n = 7 and array[] = {1, 2, 3, 1, 3, 6, 6}
Output: 1, 3, 6
Explanation: The numbers 1 , 3 and 6 appears more
than once in the array.
Input : n = 5 and array[] = {1, 2, 3, 4 ,3}
Output: 3
Explanation: The number 3 appears more than once
in the array.
This problem is an extended version of the following problem.
Find the two repeating elements in a given array
Method 1 and Method 2 of the above link are not applicable as the question says O(n) time complexity and O(1) constant space. Also, Method 3 and Method 4 cannot be applied here because there can be more than 2 repeating elements in this problem. Method 5 can be extended to work for this problem. Below is the solution that is similar to Method 5.
Solution 1:
- Approach:The elements in the array is from 0 to n-1 and all of them are positive. So to find out the duplicate elements, a HashMap is required, but the question is to solve the problem in constant space. There is a catch, the array is of length n and the elements are from 0 to n-1 (n elements). The array can be used as a HashMap.
- Algorithm:
- Traverse the array from start to end.
- For every element,take its absolute value and if the abs(array[i])‘th element is positive, the element has not encountered before, else if negative the element has been encountered before print the absolute value of the current element.
-
Implementation:
C++
// C++ code to find// duplicates in O(n) time#include <bits/stdc++.h>usingnamespacestd;// Function to print duplicatesvoidprintRepeating(intarr[],intsize){inti;cout <<"The repeating elements are:"<< endl;for(i = 0; i < size; i++){if(arr[abs(arr[i])] >= 0)arr[abs(arr[i])] = -arr[abs(arr[i])];elsecout <<abs(arr[i]) <<" ";}}// Driver Codeintmain(){intarr[] = {1, 2, 3, 1, 3, 6, 6};intarr_size =sizeof(arr)/sizeof(arr[0]);printRepeating(arr, arr_size);return0;}// This code is contributed// by Akanksha Raichevron_rightfilter_noneC
// C code to find// duplicates in O(n) time#include <stdio.h>#include <stdlib.h>// Function to print duplicatesvoidprintRepeating(intarr[],intsize){inti;printf("The repeating elements are: \n");for(i = 0; i < size; i++){if(arr[abs(arr[i])] >= 0)arr[abs(arr[i])] = -arr[abs(arr[i])];elseprintf(" %d ",abs(arr[i]));}}intmain(){intarr[] = {1, 2, 3, 1, 3, 6, 6};intarr_size =sizeof(arr)/sizeof(arr[0]);printRepeating(arr, arr_size);getchar();return0;}chevron_rightfilter_noneJava
// Java code to find// duplicates in O(n) timeclassFindDuplicate{// Function to print duplicatesvoidprintRepeating(intarr[],intsize){inti;System.out.println("The repeating elements are : ");for(i =0; i < size; i++){if(arr[ Math.abs(arr[i])] >=0)arr[ Math.abs(arr[i])] = -arr[ Math.abs(arr[i])];elseSystem.out.print(Math.abs(arr[i]) +" ");}}// Driver programpublicstaticvoidmain(String[] args){FindDuplicate duplicate =newFindDuplicate();intarr[] = {1,2,3,1,3,6,6};intarr_size = arr.length;duplicate.printRepeating(arr, arr_size);}}// This code has been contributed by Mayank Jaiswalchevron_rightfilter_nonePython3
# Python3 code to find# duplicates in O(n) time# Function to print duplicatesdefprintRepeating(arr, size):print("The repeating elements are: ")foriinrange(0, size):ifarr[abs(arr[i])] >=0:arr[abs(arr[i])]=-arr[abs(arr[i])]else:print(abs(arr[i]), end=" ")# Driver codearr=[1,2,3,1,3,6,6]arr_size=len(arr)printRepeating(arr, arr_size)# This code is contributed by Shreyanshi Arun.chevron_rightfilter_noneC#
// C# code to find// duplicates in O(n) timeusingSystem;classGFG{staticvoidprintRepeating(int[]arr,intsize){inti;Console.Write("The repeating"+" elements are : ");for(i = 0; i < size; i++){if(arr[ Math.Abs(arr[i])] >= 0)arr[ Math.Abs(arr[i])] =-arr[ Math.Abs(arr[i])];elseConsole.Write(Math.Abs(arr[i]) +" ");}}// Driver programpublicstaticvoidMain(){int[]arr = {1, 2, 3, 1, 3, 6, 6};intarr_size = arr.Length;printRepeating(arr, arr_size);}}// This code is contributed by Sam007chevron_rightfilter_nonePHP
<?php// PHP program to Find duplicates in O(n)// time and O(1) extra space | Set 1functionprintRepeating($arr,$size){echo"The repeating elements are: \n";for($i= 0;$i<$size;$i++){if($arr[abs($arr[$i])] >= 0)$arr[abs($arr[$i])] = -$arr[abs($arr[$i])];elseechoabs($arr[$i]) ." ";}}// Driver Code$arr=array(1, 2, 3, 1, 3, 6, 6);$arr_size=count($arr);printRepeating($arr,$arr_size);// This code is contributed by Sam007?>chevron_rightfilter_none -
Output:
The repeating elements are: 1 3 6
- Note: The above program doesn’t handle 0 cases (If 0 is present in array). The program can be easily modified to handle that also. It is not handled to keep the code simple.
- Complexity Analysis:
- Time Complexity: O(n), only one traversal is needed, so time complexity is O(n)
- Auxiliary Space: O(1), no extra space is required, so space complexity is constant.
There is a problem in the above approach.
It prints the repeated number more than once. For example: {1, 6, 3, 1, 3, 6, 6} it will give output as : 1 3 6 6. In below set, another approach is discussed that prints repeating elements only once.
Alternate Solution:
- Approach: The basic idea is to use a HashMap to solve the problem. But there is a catch, the numbers in the array are from 0 to n-1, and the input array has length n. So, the input array can be used as a HashMap. While Traversing the array, if an element ‘a’ is encountered then increase the value of a%n‘th element by n. The frequency can be retrieved by dividing the a % n’th element by n.
- Algorithm:
- Traverse the given array from start to end.
- For every element in the array increment the arr[i]%n‘th element by n.
- Now traverse the array again and print all those indexes i for which arr[i]/n is greater than 1. Which guarantees that the number n has been added to that index
- This approach works because all elements are in the range from 0 to n-1 and arr[i] would be greater than n only if a value “i” has appeared more than once.
- Implementation:
C++
// C++ code to find// duplicates in O(n) time#include <bits/stdc++.h>usingnamespacestd;intmain(){intnumRay[] = {0, 4, 3, 2, 7, 8, 2, 3, 1};intarr_size =sizeof(numRay) /sizeof(numRay[0]);for(inti = 0; i < arr_size; i++){numRay[numRay[i] % arr_size] = numRay[numRay[i] % arr_size] + arr_size;}cout <<"The repeating elements are : "<< endl;for(inti = 0; i < arr_size; i++){if(numRay[i] >= arr_size*2){cout << i <<" "<< endl;}}return0;}// This code is contributed by PrinciRaj1992chevron_rightfilter_noneJava
classLeet442 {publicstaticvoidmain(String args[]) {intnumRay[] = {0,4,3,2,7,8,2,3,1};for(inti =0; i < numRay.length; i++) {numRay[numRay[i] % numRay.length] = numRay[numRay[i] % numRay.length] + numRay.length;}System.out.println("The repeating elements are : ");for(inti =0; i < numRay.length; i++) {if(numRay[i] >= numRay.length*2) {System.out.println(i +" ");}}}}chevron_rightfilter_nonePython
# Python3 code to find duplicates in O(n) timenumRay=[0,4,3,2,7,8,2,3,1];arr_size=len(numRay);foriinrange(arr_size):numRay[numRay[i]%arr_size]=numRay[numRay[i]%arr_size]+arr_size;print("The repeating elements are : ");foriinrange(arr_size):if(numRay[i] >=arr_size*2):print(i," ");# This code is contributed by 29AjayKumarchevron_rightfilter_none - Output:
The repeating elements are : 2 3
- Complexity Anlaysis:
- Time Complexity: O(n).
Only two traversals are needed. So the time complexity is O(n). - Auxiliary Space: O(1).
No extra space is needed, so the space complexity is constant.
- Time Complexity: O(n).
- Duplicates in an array in O(n) time and by using O(1) extra space | Set-3
- Find the maximum repeating number in O(n) time and O(1) extra space
- Duplicates in an array in O(n) and by using O(1) extra space | Set-2
- Count frequencies of all elements in array in O(1) extra space and O(n) time
- Rearrange positive and negative numbers in O(n) time and O(1) extra space
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Find duplicates in constant array with elements 0 to N-1 in O(1) space
- Find median of BST in O(n) time and O(1) space
- Shuffle array {a1, a2, .. an, b1, b2, .. bn} as {a1, b1, a2, b2, a3, b3, ……, an, bn} without using extra space
- K'th smallest element in BST using O(1) Extra Space
- Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space
- Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space
- Merge two BSTs with limited extra space
- Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ......, an, bn} without using extra space
- k smallest elements in same order using O(1) extra space
- Merge two sorted arrays with O(1) extra space
- Connect nodes at same level using constant extra space
- Efficiently merging two sorted arrays with O(1) extra space
- Move all negative elements to end in order with extra space allowed
- Rearrange an array in maximum minimum form | Set 2 (O(1) extra space)
Duplicates in an array in O(n) and by using O(1) extra space | Set-2
Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

