Open In App

Count Subarrays of 1 in Binary Array

Last Updated : 17 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, the array contains only 1s and 0s, and the task is to return the count of the total number of subarrays where all the elements of the subarrays are 1.

Examples:

Input: N = 4, arr[] = {1, 1, 1, 0}
Output: 6
Explanation: Subarrays of 1 will look like the following: [1], [1, 1], [1, 1, 1], [1], [1, 1], [1]

Input: N = 5, arr[] = {1, 1, 1, 0, 1}
Output: 7

Naive Approach: To solve the problem follow the below idea:

Generate all the subarrays of the given array and count the subarrays of 1s.

Steps that were to follow the above approach:

  • Initialize a counter variable with 0 to count the subarrays of 1s.
  • Use nested (three) for/while loops for generating all the subarrays of the given array. 
  • The first loop will indicate the start of the subarray,  
    • The second will indicate the ending of the subarray and,  
      • The third loop will start traversal from start to end.
  • While the inner loop is traversing the subarray, initialize the boolean variable to true to keep track of the subarray elements:
    •  If any element in the subarray that is arr[k] where k ≥ i and k ≤ j is not 1, update this boolean variable to false. 
  • If the boolean variable is still true, means all the elements in subarrays are 1. Increment the counter variable.
  • Return the count of the subarrays of 1s.

Below is the code to implement the above steps:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate no. of
// subarrays of 1s.
void no_of_subarrays(int n, vector<int>& arr)
{
 
    // Initialize the count = 0
    // to count the subarrays.
    int countofsub = 0;
 
    // Outer for loop
    for (int i = 0; i < n; i++) {
 
        // Inner1 for loop
        for (int j = i; j < n; j++) {
 
            // varibale to keep track
            // of continuous 1's.
            bool b = true;
 
            // Inner2 loop to generate
            // all subarrays.
            for (int k = i; k <= j; k++) {
 
                // Print subarray element.
                cout << arr[k] << " ";
 
                // If subarray element is
                // not 1, 0 make flag
                // variable false.
                if (arr[k] != 1) {
                    b = false;
                }
            }
            cout << endl;
 
            // If all the elements in
            // subarray are 1, increment
            // the count.
            if (b) {
                countofsub++;
            }
        }
    }
    cout << "Total No. of subarrays of 1's are: "
         << countofsub << endl;
}
 
// Drivers code
int main()
{
 
    vector<int> arr = { 1, 1, 1, 0 };
 
    // Function Call
    no_of_subarrays(4, arr);
    return 0;
}


Java




// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.ArrayList;
import java.util.List;
 
class Main {
    // Function to calculate no. of
    // subarrays of 1s.
    static void no_of_subarrays(int n, List<Integer> arr) {
        // Initialize the count = 0
        // to count the subarrays.
        int countofsub = 0;
        // Outer for loop
        for (int i = 0; i < n; i++) {
            // Inner1 for loop
            for (int j = i; j < n; j++) {
                // variable to keep track
                // of continuous 1's.
                boolean b = true;
                // Inner2 loop to generate
                // all subarrays.
                for (int k = i; k <= j; k++) {
                    // Print subarray element.
                    System.out.print(arr.get(k) + " ");
                    // If subarray element is
                    // not 1, 0 make flag
                    // variable false.
                    if (arr.get(k) != 1) {
                        b = false;
                    }
                }
                System.out.println();
                // If all the elements in
                // subarray are 1, increment
                // the count.
                if (b) {
                    countofsub++;
                }
            }
        }
        System.out.println("Total No. of subarrays of 1's are: " + countofsub);
    }
    // Drivers code
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(1);
        arr.add(1);
        arr.add(0);
        // Function Call
        no_of_subarrays(4, arr);
    }
}
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}


Python3




# python code for above approach
 
def no_of_subarrays(n, arr):
    # Initialize the count to 0
    count_of_sub = 0
 
    # Outer loop
    for i in range(n):
 
        # Inner 1 loop
        for j in range(i, n):
 
            # Variable to keep track of continuous 1's
            b = True
 
            # Inner 2 loop to generate all subarrays
            for k in range(i, j + 1):
 
                # Print subarray element
                print(arr[k], end=" ")
 
                # If subarray element is not 1 or 0, set flag variable to false
                if arr[k] != 1:
                    b = False
 
            print()
 
            # If all elements in subarray are 1, increment the count
            if b:
                count_of_sub += 1
 
    print("Total number of subarrays of 1's are:", count_of_sub)
 
 
# Driver code
arr = [1, 1, 1, 0]
 
# Function call
no_of_subarrays(4, arr)


C#




using System;
using System.Collections.Generic;
 
class Program
{
      // Function to calculate no. of
    // subarrays of 1s.
    static void no_of_subarrays(int n, List<int> arr)
    {
       
          // Initialize the count = 0
            // to count the subarrays.
        int countofsub = 0;
 
       
          // Outer for loop
        for (int i = 0; i < n; i++)
        {
              // Inner1 for loop
            for (int j = i; j < n; j++)
            {
               
                  // varibale to keep track
                 // of continuous 1's.
                bool b = true;
                 
                  // Inner2 loop to generate
                // all subarrays.
                for (int k = i; k <= j; k++)
                {
                   
                      // Print subarray element.
                    Console.Write(arr[k] + " ");
 
                   
                      // If subarray element is
                        // not 1, 0 make flag
                    // variable false.
                    if (arr[k] != 1)
                    {
                        b = false;
                    }
                }
                Console.WriteLine();
 
                  // If all the elements in
                    // subarray are 1, increment
                // the count.
                if (b)
                {
                    countofsub++;
                }
            }
        }
        Console.WriteLine("Total No. of subarrays of 1's are: " + countofsub);
    }
 
      // Drivers code
    static void Main(string[] args)
    {
        List<int> arr = new List<int> { 1, 1, 1, 0 };
 
        no_of_subarrays(4, arr);
    }
}


Javascript




// Function to calculate no. of
// subarrays of 1s.
function no_of_subarrays(n, arr)
{
 
    // Initialize the count = 0
    // to count the subarrays.
    let countofsub = 0;
 
    // Outer for loop
    for (let i = 0; i < n; i++)
    {
     
        // Inner1 for loop
        for (let j = i; j < n; j++)
        {
         
            // varibale to keep track
            // of continuous 1's.
            let b = true;
             
            // Inner2 loop to generate
            // all subarrays.
            for (let k = i; k <= j; k++)
            {
             
                // Print subarray element.
                process.stdout.write(arr[k] + " ");
 
                // If subarray element is
                // not 1, 0 make flag
                // variable false.
                if (arr[k] != 1) {
                    b = false;
                }
            }
            process.stdout.write("\n");
 
            // If all the elements in
            // subarray are 1, increment
            // the count.
            if (b) {
                countofsub++;
            }
        }
    }
    console.log("Total No. of subarrays of 1's are: " + countofsub);
}
 
// Drivers code
let arr = [ 1, 1, 1, 0 ];
no_of_subarrays(4, arr);
 
// This code is contributed by Tushar Rokade


Output

1 
1 1 
1 1 1 
1 1 1 0 
1 
1 1 
1 1 0 
1 
1 0 
0 
Total No. of subarrays of 1's are: 6






Time Complexity: O(n3)
Auxiliary Space: O(1)

Efficient Approach: To solve the problem follow the below idea:

The optimal approach is to find out the groups of continuous 1s in the array and for each group of continuous 1s, calculate the number of subarrays. 

Steps that were to follow the above approach:

  • Initialize two variables with 0. The first variable will count no. of continuous 1s and the second will count the no. of subarrays of 1s.
  • Traverse the arrays using a single for loop. 
    • Check the arr[i] element, where i ≥ 0 and i < n. 
    • If the arr[i] element is 1, increment the first variable. 
    • If at any index i, arr[i] is not 1, our task is to calculate the subarrays of the group of continuous 1s using the simple mathematics formula first_variable*(first_variable+1)/2. 
  • Update the second variable with calculated subarrays. 
  • Reinitialize the first variable with 0 to count the next upcoming group of continuous 1s.
  • After completing the traversal, once again calculate the subarrays, because, for arr[n-1] = 1, you will go to the else condition to calculate the subarrays.
  • Return the count of subarrays.

Below is the code to implement the above steps:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate no. of
// subarrays of 1s.
int no_of_subarrays(int n, vector<int>& arr)
{
 
    // Step 1 - initialization of
    // tracking vaiables.
    int ones = 0, count = 0;
 
    // Step -2 Iterating the array
    // using loop.
    for (int i = 0; i < n; i++) {
 
        // Step - 3 Condition to check
        // whether the array element
        // is 1 or not.
        if (arr[i] == 1) {
 
            // If it is 1 increment
            // the variable - ones.
            ones++;
        }
        else {
 
            // If array element is not 1.
            // Step 4 - Calculate no. of
            // subarrays till index i
            // using formula.
 
            // Update the count variable.
            count += ones * (ones + 1) / 2;
 
            // Step - 5 Reinitialize ones
            // to again calculate continuous
            // subarry of 1.
            ones = 0;
        }
    }
 
    // Step - 6 At last again calculate
    // subarrays
    count += ones * (ones + 1) / 2;
 
    // Step - 7 Return the count of
    // subarrays of 1.
    return count;
}
 
// Drivers code
int main()
{
 
    vector<int> arr = { 1, 1, 1, 0 };
 
    // Function Call
    cout << no_of_subarrays(4, arr) << endl;
    return 0;
}


Java




// A Java program to calculate the number of subarrays of 1s in a given array.
import java.util.*;
 
public class SubarraysOf1s {
 
    /*
      Function to calculate the number of subarrays of 1s.
       
      @param n   the size of the array.
      @param arr the input array.
      @return the number of subarrays of 1s.
     */
    public static int noOfSubarrays(int n, List<Integer> arr) {
 
        // Step 1 - Initialization of tracking variables.
        int ones = 0, count = 0;
 
        // Step 2 - Iterating the array using a loop.
        for (int i = 0; i < n; i++) {
 
            // Step 3 - Condition to check whether the array element is 1 or not.
            if (arr.get(i) == 1) {
 
                // If it is 1 increment the variable - ones.
                ones++;
            } else {
 
                // If array element is not 1.
                // Step 4 - Calculate no. of subarrays till index i using formula.
 
                // Update the count variable.
                count += ones * (ones + 1) / 2;
 
                // Step 5 - Reinitialize ones to again calculate continuous subarray of 1.
                ones = 0;
            }
        }
 
        // Step 6 - At last again calculate subarrays
        count += ones * (ones + 1) / 2;
 
        // Step 7 - Return the count of subarrays of 1.
        return count;
    }
 
    // Driver's code
    public static void main(String[] args) {
 
        List<Integer> arr = new ArrayList<>(Arrays.asList(1, 1, 1, 0));
 
        // Function Call
        System.out.println(noOfSubarrays(4, arr));
    }
}


Python3




# Function to calculate no. of
# subarrays of 1s.
def no_of_subarrays(n, arr):
   
      # Step 1 - initialization of
    # tracking vaiables.
    ones = 0
    count = 0
     
    # Step -2 Iterating the array
    # using loop.
    for i in range(n):
           
        # Step - 3 Condition to check
        # whether the array element
        # is 1 or not.
        if arr[i] == 1:
              # If it is 1 increment
            # the variable - ones.
            ones += 1
        else:
              # If array element is not 1.
            # Step 4 - Calculate no. of
            # subarrays till index i
            # using formula.
             # Update the count variable.
            count += ones * (ones + 1) // 2
             
            # Step - 5 Reinitialize ones
            # to again calculate continuous
            # subarry of 1.
            ones = 0
     
     
    # Step - 6 At last again calculate
    # subarrays
    count += ones * (ones + 1) // 2
     
    # Step - 7 Return the count of
    # subarrays of 1.
    return count
 
# Driver code
arr = [1, 1, 1, 0]
print(no_of_subarrays(4, arr))


C#




// C# code implementation:
 
using System;
 
public class GFG {
 
    // Function to calculate the number of subarray of 1s.
    static int noOfSubarrays(int n, int[] arr)
    {
        // Step 1 - Initialization of tracking variables.
        int ones = 0, count = 0;
 
        // Step 2 - Iterating the array using a loop.
        for (int i = 0; i < n; i++) {
            // Step 3 - Condition to check whether the array
            // element is 1 or not.
            if (arr[i] == 1) {
                ones++;
            }
            else {
                // If array element is not 1.
                // Step 4 - Calculate no. of subarrays till
                // index i using formula.
 
                // Update the count variable.
                count += ones * (ones + 1) / 2;
                // Step 5 - Reinitialize ones to again
                // calculate continuous subarray of 1.
                ones = 0;
            }
        }
        // Step 6 - At last again calculate subarrays
        count += ones * (ones + 1) / 2;
 
        // Step 7 - Return the count of subarrays of 1.
        return count;
    }
 
    static public void Main()
    {
 
        // Code
        int[] arr = { 1, 1, 1, 0 };
 
        // Function call
        Console.WriteLine(noOfSubarrays(4, arr));
    }
}
 
// This code is contributed by sankar.


Javascript




// Function to calculate the number of subarrays of 1s.
function numberOfSubarrays(n, arr) {
    // Step 1 - Initialization of tracking variables.
    let ones = 0;
    let count = 0;
 
    // Step 2 - Iterating the array using a loop.
    for (let i = 0; i < n; i++) {
        // Step 3 - Condition to check whether the array element is 1 or not.
        if (arr[i] === 1) {
            // If it is 1, increment the variable - ones.
            ones++;
        } else {
            // If the array element is not 1.
            // Step 4 - Calculate the number of subarrays till index i using formula.
 
            // Update the count variable.
            count += (ones * (ones + 1)) / 2;
 
            // Step 5 - Reinitialize ones to again calculate continuous subarray of 1.
            ones = 0;
        }
    }
 
    // Step 6 - At last, again calculate subarrays.
    count += (ones * (ones + 1)) / 2;
 
    // Step 7 - Return the count of subarrays of 1.
    return count;
}
 
// Driver code
const arr = [1, 1, 1, 0];
 
// Function Call
console.log(numberOfSubarrays(4, arr));


Output

6






Time Complexity: O(n)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads