An interveiewer asked me below question:
Search out unique integer values(approx. 1000) from a sorted array of billion records(like 1,1,1,1,3,3,3,4,5,5,6,6,6,6,6,7,7,7,7,7,7,8,8,8,8...........) with complexity less than O(n).
NOTE: NOt to use SET.
One solution that i tried to implement:
Divide that array into two set of arrays,then iterate both subarrays and search in hashmap if element doesnot exit,then add it into hashmap otherwise move to next iteration.
public static void main(String[] args) {
int arr[] = {1,2,4,9,-3,5,6,3,6,12,5,6,2,-1,-3,6,87,9,2,3,5,7,9,1,0,1,3,5,7,6,3,8,6,3,21,45,6};
int size1 =0, size2 = 0;
HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
System.out.println("length of Array:"+arr.length);
if((arr.length)%2 == 0){
size1 = size2 = arr.length/2;
}else{
size1 = (arr.length + 1)/2;
size2 = (arr.length)/2;
}
for(int i=0;((size1-i-1)>= 0)||((size2+i)<(arr.length - 1));i++){
if(map.containsKey(arr[size1 -i-1])== false){
map.put(arr[size1 -i-1],arr[size1 -i-1]);
}
if(map.containsKey(arr[size2 + i]) == false){
map.put(arr[size2 + i], arr[size2 + i]);
}
}
System.out.println(map.keySet());
}
And its working as expected, then he asked what if we divide the array into n sets?
then the complexity would be O(1) or O(n/n)? Is it possible?
Please suggest if there is another way to implement the same without using hashmap?