Open In App

Find Duplicates of array using bit array

Last Updated : 23 Feb, 2023
Comments
Improve
Suggest changes
6 Likes
Like
Report

You have an array of N numbers, where N is at most 32,000. The array may have duplicate entries and you do not know what N is. With only 4 Kilobytes of memory available, how would print all duplicate elements in the array ?. 

Examples:

Input : arr[] = {1, 5, 1, 10, 12, 10}
Output : 1 10
1 and 10 appear more than once in given
array.

Input : arr[] = {50, 40, 50}
Output : 50

Asked In: Amazon 

We have 4 Kilobytes of memory which means we can address up to 8 * 4 * 210 bits. Note that 32 * 210 bits is greater than 32000. We can create a bit with 32000 bits, where each bit represents one integer. Note: If you need to create a bit with more than 32000 bits, then you can create easily more and more than 32000; Using this bit vector, we can then iterate through the array, flagging each element v by setting bit v to 1. When we come across a duplicate element, we print it. Below is the implementation of the idea.

Implementation:

C++
Java Python3 C# JavaScript

Output
1 10 

Time Complexity: O(N)

Space Complexity: O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads