VOOZH about

URL: https://www.geeksforgeeks.org/dsa/duplicates-array-using-o1-extra-space-set-2/

⇱ Duplicates in an array in O(n) and by using O(1) extra space - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

Given an array arr[] of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. The task is to find the repeating numbers.

Note: The repeating element should be printed only once.

Example:

Input: n = 7, arr[] = [1, 2, 3, 6, 3, 6, 1]
Output: 1, 3, 6
Explanation: The numbers 1 , 3 and 6 appears more than once in the array.

Input : n = 5, arr[] = [1, 2, 3, 4 ,3]
Output: 3
Explanation: The number 3 appears more than once in the array.

Please refer to Duplicates in an array in O(n) and by using O(n) extra space for implementation of naive approach.

Approach:

The basic idea is based on the hash map to solve the problem. But, the numbers in the array are from 0 to n-1, and the input array has length n. So, the input array itself can be used as a hash map. 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.

Note: This approach works because all elements are in the range from 0 to n-1 and arr[i]/n would be greater than 1 only if a value "i" has appeared more than once. 


Output
1 2 3 

Time Complexity: O(n), Only two traversals are needed. So the time complexity is O(n)
Auxiliary Space: O(1).  As no extra space is needed, so the space complexity is constant

Comment
Article Tags:
Article Tags: