Find duplicates in O(n) time and O(n) extra space.

Posted by on Mar 31, 2024

Given an array of n elements that contains numbers from 0 to n-1, with any of these numbers appearing any number of times in any order (non-sorted).

Find these repeating numbers in O(n) time and O(n) memory space.

Return -1 if there is no duplicate.

Input: {0, 3, 1, 2}
Output: -1

Input: {2, 3, 1, 0, 3, 2, 3, 0}
Output: 3, 2, 0


Solutions

Method 1: Using an extra array of length "n"

Traverse the given array and keep track of the count of all elements in the array using a temporary array tmp[] of size n.

When you see an element whose count is already "1" print it. This specific "tmp[arr[i]] == 1" check will handle scenarios where an element occurs more than 2 times.

This method uses the range given in the question to restrict the size of tmp[].

Complexity

The time complexity of this solution is O(n) and space complexity is O(n).

Related


Find duplicates in O(n) time and O(1) extra space

Maximum Product Subarray (Modified Kadane's Algorithm)

Move all negative numbers to beginning of the array

Find maximum and minimum element of an array

Program to right rotate an array by 'k' elements

Segregate 0s, 1s and 2s in an array (Sort an array of 0s, 1s and 2s)

Minimize the difference between the heights of smallest and highest tower

Segregate 0s and 1s in an array (Sort an array of 0s and 1s)

Find largest sum contiguous sub-array (Kadane's Algorithm)

Alternating +ve & -ve in array in O(1) time (maintaining order)