Count Subarrays of 1 in Binary Array
Last Updated :
17 Oct, 2023
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++
#include <bits/stdc++.h>
using namespace std;
void no_of_subarrays( int n, vector< int >& arr)
{
int countofsub = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i; j < n; j++) {
bool b = true ;
for ( int k = i; k <= j; k++) {
cout << arr[k] << " " ;
if (arr[k] != 1) {
b = false ;
}
}
cout << endl;
if (b) {
countofsub++;
}
}
}
cout << "Total No. of subarrays of 1's are: "
<< countofsub << endl;
}
int main()
{
vector< int > arr = { 1, 1, 1, 0 };
no_of_subarrays(4, arr);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
class Main {
static void no_of_subarrays( int n, List<Integer> arr) {
int countofsub = 0 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = i; j < n; j++) {
boolean b = true ;
for ( int k = i; k <= j; k++) {
System.out.print(arr.get(k) + " " );
if (arr.get(k) != 1 ) {
b = false ;
}
}
System.out.println();
if (b) {
countofsub++;
}
}
}
System.out.println( "Total No. of subarrays of 1's are: " + countofsub);
}
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
arr.add( 1 );
arr.add( 1 );
arr.add( 1 );
arr.add( 0 );
no_of_subarrays( 4 , arr);
}
}
class HelloWorld {
public static void main(String[] args) {
System.out.println( "Hello, World!" );
}
}
|
Python3
def no_of_subarrays(n, arr):
count_of_sub = 0
for i in range (n):
for j in range (i, n):
b = True
for k in range (i, j + 1 ):
print (arr[k], end = " " )
if arr[k] ! = 1 :
b = False
print ()
if b:
count_of_sub + = 1
print ( "Total number of subarrays of 1's are:" , count_of_sub)
arr = [ 1 , 1 , 1 , 0 ]
no_of_subarrays( 4 , arr)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static void no_of_subarrays( int n, List< int > arr)
{
int countofsub = 0;
for ( int i = 0; i < n; i++)
{
for ( int j = i; j < n; j++)
{
bool b = true ;
for ( int k = i; k <= j; k++)
{
Console.Write(arr[k] + " " );
if (arr[k] != 1)
{
b = false ;
}
}
Console.WriteLine();
if (b)
{
countofsub++;
}
}
}
Console.WriteLine( "Total No. of subarrays of 1's are: " + countofsub);
}
static void Main( string [] args)
{
List< int > arr = new List< int > { 1, 1, 1, 0 };
no_of_subarrays(4, arr);
}
}
|
Javascript
function no_of_subarrays(n, arr)
{
let countofsub = 0;
for (let i = 0; i < n; i++)
{
for (let j = i; j < n; j++)
{
let b = true ;
for (let k = i; k <= j; k++)
{
process.stdout.write(arr[k] + " " );
if (arr[k] != 1) {
b = false ;
}
}
process.stdout.write( "\n" );
if (b) {
countofsub++;
}
}
}
console.log( "Total No. of subarrays of 1's are: " + countofsub);
}
let arr = [ 1, 1, 1, 0 ];
no_of_subarrays(4, arr);
|
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++
#include <bits/stdc++.h>
using namespace std;
int no_of_subarrays( int n, vector< int >& arr)
{
int ones = 0, count = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] == 1) {
ones++;
}
else {
count += ones * (ones + 1) / 2;
ones = 0;
}
}
count += ones * (ones + 1) / 2;
return count;
}
int main()
{
vector< int > arr = { 1, 1, 1, 0 };
cout << no_of_subarrays(4, arr) << endl;
return 0;
}
|
Java
import java.util.*;
public class SubarraysOf1s {
public static int noOfSubarrays( int n, List<Integer> arr) {
int ones = 0 , count = 0 ;
for ( int i = 0 ; i < n; i++) {
if (arr.get(i) == 1 ) {
ones++;
} else {
count += ones * (ones + 1 ) / 2 ;
ones = 0 ;
}
}
count += ones * (ones + 1 ) / 2 ;
return count;
}
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>(Arrays.asList( 1 , 1 , 1 , 0 ));
System.out.println(noOfSubarrays( 4 , arr));
}
}
|
Python3
def no_of_subarrays(n, arr):
ones = 0
count = 0
for i in range (n):
if arr[i] = = 1 :
ones + = 1
else :
count + = ones * (ones + 1 ) / / 2
ones = 0
count + = ones * (ones + 1 ) / / 2
return count
arr = [ 1 , 1 , 1 , 0 ]
print (no_of_subarrays( 4 , arr))
|
C#
using System;
public class GFG {
static int noOfSubarrays( int n, int [] arr)
{
int ones = 0, count = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] == 1) {
ones++;
}
else {
count += ones * (ones + 1) / 2;
ones = 0;
}
}
count += ones * (ones + 1) / 2;
return count;
}
static public void Main()
{
int [] arr = { 1, 1, 1, 0 };
Console.WriteLine(noOfSubarrays(4, arr));
}
}
|
Javascript
function numberOfSubarrays(n, arr) {
let ones = 0;
let count = 0;
for (let i = 0; i < n; i++) {
if (arr[i] === 1) {
ones++;
} else {
count += (ones * (ones + 1)) / 2;
ones = 0;
}
}
count += (ones * (ones + 1)) / 2;
return count;
}
const arr = [1, 1, 1, 0];
console.log(numberOfSubarrays(4, arr));
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...