-2

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));
6
  • 2
    is that necessary? why cant a for loop work? binary meaning 0 or 1, so count all 0s (or all 1s) using one iteration of a for loop, then array.size() - numOfZeroes. In any case, it will still be O(N) Commented Nov 19, 2023 at 6:57
  • also, regarding "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 here Commented Nov 19, 2023 at 7:17
  • 1
    The optimal solution does not involve either maps or streams. Just a for loop and two int counters. It is O(N) ... as are solutions using maps or streams ... but it will be significantly more efficient. Commented Nov 19, 2023 at 7:45
  • No such thing as a "binary array" in Java. Commented Nov 19, 2023 at 8:18
  • 1
    I believe any approach here is going to produce O(n). For example, to achieve O(1) you would need to first sort the values, which is typically O(n²). Commented Nov 19, 2023 at 16:32

3 Answers 3

2

please let me know if there is a better approach

int[] array = new int[]{1, 1, 0, 1, 0, 1, 0, 0, 0};
int ones = 0;
for (int bit : array) {
   if (bit == 1) {
       ones++;
   } 
}
System.out.println("0 : " + (array.length - ones)); 
System.out.println("1 : " + ones); 

There are significant overheads in Map data structures, and many stream-based solution involve a Map under the hood. For the smarter stream-based solutions, you still have the problem that the stream / filter / count steps involve hidden overheads that may be hard for the JIT compiler to eliminate.

So, if your primary concern is efficiency, you should use a "dumb" loop that the JIT compiler can optimize well.

Sign up to request clarification or add additional context in comments.

Comments

1

Sum the array

Java has no "binary array".

But if the array is simply whole numbers whose values come from a domain of only zero and one, then you can sum the array.

  1. The sum is the count of 1 values.
  2. Subtract the sum from the size of the array to get a count of 0 values.

Example code:

long[] numbers = { 0L , 1L , 0L } ;
long countOnes = Arrays.stream( numbers ).sum() ;
long countZeros = ( numbers.length - countOnes ) ;

See this code run at Ideone.com.

numbers.length: 3
countOnes: 1
countZeros: 2

3 Comments

Given that the max array size in Java is less than 2^31, integer overflow will not be an issue ... for this problem.
@StephenC But could be a problem for the smaller types of byte and short.
How so? The max array size is (AFAIK) the same for all element types. It is limited to the range of non-negative int values (minus a small delta). The .length "field" has type int.
0

I agreed, the simplest and fastest is just iteration over the array - and it's O(n). The only difference to those answers is not to count the '1' and get the count of '0' by lenght-count1, but explicitally counting '0' too, so that if someone ever pass something else (like for example a 2 or -1) it isn't counted wrongly.

One of the most difficult part of being a programmer is dealing with exceptional inputs and errors. If I were an interviewer I would rate as gold the ability of the candidate to think about error and exception management over the actual functionality. Because the functionality sooner or later can be implemented successfully, but poor error management can stay forever building a huge technical debt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.