I was asked this question in an interview to count the number 1 and 0 in a binary array
eg: arr = 1, 1, 0, 1, 0, 1, 0, 0, 0. We should not use Array.sort or Collections.sort function.
I could think of using stream with filter and count operation as one approach and other approach of adding the elements into hashmap and printing the count.
I have read that filter will be using iteration internally and the worst case time complexity is o(n). But in the case of hashmap, we have to loop through array , and then calculate hash to add elements. I guess stream will be a better option here. Is this correct. Please pour in your thoughts on these and please let me know if there is a better approach
int[] array = new int[]{1, 1, 0, 1, 0, 1, 0, 0, 0};
// find count of one and zero
Map<Integer,Integer> integerMap = new HashMap<>();
for(int i : array){
if(integerMap.containsKey(i)){
integerMap.put(i, integerMap.get(i) + 1);
} else {
integerMap.put(i,1);
}
}
integerMap.forEach((key, value) -> System.out.println(key + " " + value));
"filter will be using iteration internally", I wouldnt say that the filter operation uses iteration, but more like the stream itself uses iteration and all those intermediate operations are included into each loop of that iteration. See hereforloop and twointcounters. It isO(N)... as are solutions using maps or streams ... but it will be significantly more efficient.