Find the duplicate numbers in an integer array of size n that contains elements between 1 and n, at least one of which repeats.

For example,

Input: nums[] = [5, 3, 4, 2, 5, 1, 2]
Output: [5, 2]
 
Input: [1, 2, 3]
Output: []

1. Using Frequency Map

A simple solution is to store the count of each element present in the input array in a map. Then iterate through the map and collect elements having a frequency of two or more.

The algorithm can be implemented as follows in C++, Java, and Python. We can also use a count array instead of a map, since using a map does not take advantage of the fact that all array elements lie in the range 1 and n.

C++


Download  Run Code

Output:

5 2

Java


Download  Run Code

Output:

[5, 2]

Python


Download  Run Code

Output:

{2, 5}

The time complexity of the above solution is O(n) and requires O(n) extra space for Map data structure, where n is the length of the array.

2. Using Array Indices

Since all of the array’s elements lie within the range [1,n], we can check for duplicate elements by marking array elements as negative using the array index as a key. For each element in the array nums[i], invert the sign of the element present at the index i-1. However, if the element at the index i-1 is already negative, then it is repeated.

Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

5 2

Java


Download  Run Code

Output:

[5, 2]

Python


Download  Run Code

Output:

{2, 5}

The time complexity of the above solution is O(n) and requires O(1) extra space, where n is the length of the array.