![]() |
VOOZH | about |
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.
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