Find Duplicates of array using bit array
Last Updated :
23 Feb, 2023
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++
// C++ program to print all Duplicates in array
#include <bits/stdc++.h>
using namespace std;
// A class to represent an array of bits using
// array of integers
class BitArray
{
int *arr;
public:
BitArray() {}
// Constructor
BitArray(int n)
{
// Divide by 32. To store n bits, we need
// n/32 + 1 integers (Assuming int is stored
// using 32 bits)
arr = new int[(n >> 5) + 1];
}
// Get value of a bit at given position
bool get(int pos)
{
// Divide by 32 to find position of
// integer.
int index = (pos >> 5);
// Now find bit number in arr[index]
int bitNo = (pos & 0x1F);
// Find value of given bit number in
// arr[index]
return (arr[index] & (1 << bitNo)) != 0;
}
// Sets a bit at given position
void set(int pos)
{
// Find index of bit position
int index = (pos >> 5);
// Set bit number in arr[index]
int bitNo = (pos & 0x1F);
arr[index] |= (1 << bitNo);
}
// Main function to print all Duplicates
void checkDuplicates(int arr[], int n)
{
// create a bit with 32000 bits
BitArray ba = BitArray(320000);
// Traverse array elements
for (int i = 0; i < n; i++)
{
// Index in bit array
int num = arr[i];
// If num is already present in bit array
if (ba.get(num))
cout << num << " ";
// Else insert num
else
ba.set(num);
}
}
};
// Driver code
int main()
{
int arr[] = {1, 5, 1, 10, 12, 10};
int n = sizeof(arr) / sizeof(arr[0]);
BitArray obj = BitArray();
obj.checkDuplicates(arr, n);
return 0;
}
// This code is contributed by
// sanjeev2552
Java
// Java program to print all Duplicates in array
import java.util.*;
import java.lang.*;
import java.io.*;
// A class to represent array of bits using
// array of integers
public class BitArray
{
int[] arr;
// Constructor
public BitArray(int n)
{
// Divide by 32. To store n bits, we need
// n/32 + 1 integers (Assuming int is stored
// using 32 bits)
arr = new int[(n>>5) + 1];
}
// Get value of a bit at given position
boolean get(int pos)
{
// Divide by 32 to find position of
// integer.
int index = (pos >> 5);
// Now find bit number in arr[index]
int bitNo = (pos & 0x1F);
// Find value of given bit number in
// arr[index]
return (arr[index] & (1 << bitNo)) != 0;
}
// Sets a bit at given position
void set(int pos)
{
// Find index of bit position
int index = (pos >> 5);
// Set bit number in arr[index]
int bitNo = (pos & 0x1F);
arr[index] |= (1 << bitNo);
}
// Main function to print all Duplicates
static void checkDuplicates(int[] arr)
{
// create a bit with 32000 bits
BitArray ba = new BitArray(320000);
// Traverse array elements
for (int i=0; i<arr.length; i++)
{
// Index in bit array
int num = arr[i] - 1;
// If num is already present in bit array
if (ba.get(num))
System.out.print(num +" ");
// Else insert num
else
ba.set(num);
}
}
// Driver code
public static void main(String[] args) throws
java.lang.Exception
{
int[] arr = {1, 5, 1, 10, 12, 10};
checkDuplicates(arr);
}
}
Python3
# Python3 program to print all Duplicates in array
# A class to represent array of bits using
# array of integers
class BitArray:
# Constructor
def __init__(self, n):
# Divide by 32. To store n bits, we need
# n/32 + 1 integers (Assuming int is stored
# using 32 bits)
self.arr = [0] * ((n >> 5) + 1)
# Get value of a bit at given position
def get(self, pos):
# Divide by 32 to find position of
# integer.
self.index = pos >> 5
# Now find bit number in arr[index]
self.bitNo = pos & 0x1F
# Find value of given bit number in
# arr[index]
return (self.arr[self.index] &
(1 << self.bitNo)) != 0
# Sets a bit at given position
def set(self, pos):
# Find index of bit position
self.index = pos >> 5
# Set bit number in arr[index]
self.bitNo = pos & 0x1F
self.arr[self.index] |= (1 << self.bitNo)
# Main function to print all Duplicates
def checkDuplicates(arr):
# create a bit with 32000 bits
ba = BitArray(320000)
# Traverse array elements
for i in range(len(arr)):
# Index in bit array
num = arr[i]
# If num is already present in bit array
if ba.get(num):
print(num, end = " ")
# Else insert num
else:
ba.set(num)
# Driver Code
if __name__ == "__main__":
arr = [1, 5, 1, 10, 12, 10]
checkDuplicates(arr)
# This code is contributed by
# sanjeev2552
C#
// C# program to print all Duplicates in array
// A class to represent array of bits using
// array of integers
using System;
class BitArray
{
int[] arr;
// Constructor
public BitArray(int n)
{
// Divide by 32. To store n bits, we need
// n/32 + 1 integers (Assuming int is stored
// using 32 bits)
arr = new int[(int)(n >> 5) + 1];
}
// Get value of a bit at given position
bool get(int pos)
{
// Divide by 32 to find position of
// integer.
int index = (pos >> 5);
// Now find bit number in arr[index]
int bitNo = (pos & 0x1F);
// Find value of given bit number in
// arr[index]
return (arr[index] & (1 << bitNo)) != 0;
}
// Sets a bit at given position
void set(int pos)
{
// Find index of bit position
int index = (pos >> 5);
// Set bit number in arr[index]
int bitNo = (pos & 0x1F);
arr[index] |= (1 << bitNo);
}
// Main function to print all Duplicates
static void checkDuplicates(int[] arr)
{
// create a bit with 32000 bits
BitArray ba = new BitArray(320000);
// Traverse array elements
for (int i = 0; i < arr.Length; i++)
{
// Index in bit array
int num = arr[i];
// If num is already present in bit array
if (ba.get(num))
Console.Write(num + " ");
// Else insert num
else
ba.set(num);
}
}
// Driver code
public static void Main()
{
int[] arr = {1, 5, 1, 10, 12, 10};
checkDuplicates(arr);
}
}
// This code is contributed by Rajput-Ji
JavaScript
// JavaScript program to print all Duplicates in array
// A class to represent array of bits using
// array of integers
class BitArray {
// Constructor
constructor(n){
// Divide by 32. To store n bits, we need
// n/32 + 1 integers (Assuming int is stored
// using 32 bits)
this.arr = new Array((n >> 5) + 1);
}
// Get value of a bit at given position
get(pos){
// Divide by 32 to find position of
// integer.
let index = (pos >> 5);
// Now find bit number in arr[index]
let bitNo = (pos & 0x1F);
// Find value of given bit number in
// arr[index]
let arrCopy = this.arr
return (arrCopy[index] & (1 << bitNo)) != 0;
}
// Sets a bit at given position
set(pos){
// Find index of bit position
var index = (pos >> 5);
// Set bit number in arr[index]
var bitNo = (pos & 0x1F);
var arr1 = this.arr;
arr1[index] = arr1[index] | (1 << bitNo);
this.arr = arr1;
}
}
// Main function to print all Duplicates
function checkDuplicates(arr){
// create a bit with 32000 bits
var ba = new BitArray(320000);
// Traverse array elements
for (var i = 0; i < arr.length; i++) {
// Index in bit array
var num = arr[i];
// If num is already present in bit array
if (ba.get(num))
console.log(num);
// Else insert num
else
ba.set(num);
}
}
// Driver code
var a = [ 1, 5, 1, 10, 12, 10 ];
checkDuplicates(a);
// This code is contributed by Kirti Agarwal(kirtiagarwal23121999)
Time Complexity: O(N)
Space Complexity: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read