Search code examples
javascriptarraysiterationcountingsequences

Detecting Sequences of Zeroes in an Array


I have some arrays and I want to count the number of sequences of zeroes in the array.

For example:

 A [0][0][1][1][1][0][0][0][2][2][2][2][0][0][0]

would return 3 sequences

How can I do this efficiently?

Edit: the language I am interested in using to solve is

Javascript


Solution

  • You can just count the zeroes that are followed by either nonzero or end-of-array. For example, in Java:

    int result = 0;
    for (int i = 0; i < A.length; ++i) {
        if (A[i] == 0 && (i + 1 == A.length || A[i+1] != 0)) {
            ++result;
        }
    }
    return result;