Sum of bitwise AND of all submatrices
Last Updated :
24 May, 2022
Given an NxN matrix, the task is to find the sum of bit-wise AND of all of its rectangular sub-matrices.
Examples:
Input : arr[][] = {{1, 1, 1},
{1, 1, 1},
{1, 1, 1}}
Output : 36
Explanation: All the possible submatrices will have AND value 1.
Since, there are 36 submatrices in total, ans = 36
Input : arr[][] = {{9, 7, 4},
{8, 9, 2},
{11, 11, 5}}
Output : 135
Prerequisite: Number of rectangular submatrices of a binary matrix with all 1s.
Naive Solution: A simple solution is to generate all the sub-matrices and find the required AND for each of them. The time complexity of this approach will be O(N6).
Efficient Approach: For the sake of better understanding, let’s assume that any bit of an element is represented by the variable 'i', and the variable 'sum' is used to store the final sum.
The idea here is, we will try to find the number of AND values(sub-matrices with bit-wise and(&)) with ith bit set. Let us suppose, there is ‘Si‘ number of sub-matrices with ith bit set. For, ith bit, the sum can be updated as sum += (2i * Si).
For each bit 'i', create a boolean matrix set_bit which stores '1' at an index (R, C) if ith bit of arr[R][C] is set. Otherwise, it stores '0'. Then, for this boolean array, we try to find the number of rectangular submatrices with all 1s(Si). For, ith bit, the final sum will be updated as:
sum += 2i * Si
Below is the implementation of the above approach:
C++
// C++ program to find sum of Bit-wise AND
// of all submatrices
#include <iostream>
#include <stack>
using namespace std;
#define n 3
// Function to find prefix-count for each row
// from right to left
void findPrefixCount(int p_arr[][n], bool set_bit[][n])
{
for (int i = 0; i < n; i++) {
for (int j = n - 1; j >= 0; j--) {
if (!set_bit[i][j])
continue;
if (j != n - 1)
p_arr[i][j] += p_arr[i][j + 1];
p_arr[i][j] += (int)set_bit[i][j];
}
}
}
// Function to find the number of submatrices
// with all 1s
int matrixAllOne(bool set_bit[][n])
{
// Array to store required prefix count of 1s from
// right to left for boolean array
int p_arr[n][n] = { 0 };
findPrefixCount(p_arr, set_bit);
// Variable to store the final answer
int ans = 0;
// For each index of a column, determine the number
// of sub-matrices starting from that index
// and has all 1s
for (int j = 0; j < n; j++) {
int i = n - 1;
// Stack to store elements and the count
// of the numbers they popped
// First part of pair is value of inserted element
// Second part is count of the number of elements
// pushed before with a greater value
stack<pair<int, int> > q;
// variable to store the number of submatrices
// with all 1s
int to_sum = 0;
while (i >= 0) {
int c = 0;
while (q.size() != 0 and q.top().first > p_arr[i][j]) {
to_sum -= (q.top().second + 1) * (q.top().first - p_arr[i][j]);
c += q.top().second + 1;
q.pop();
}
to_sum += p_arr[i][j];
ans += to_sum;
q.push({ p_arr[i][j], c });
i--;
}
}
return ans;
}
// Function to find the sum of Bitwise-AND
// of all submatrices
int sumAndMatrix(int arr[][n])
{
int sum = 0;
int mul = 1;
for (int i = 0; i < 30; i++) {
// matrix to store the status
// of ith bit of each element
// of matrix arr
bool set_bit[n][n];
for (int R = 0; R < n; R++)
for (int C = 0; C < n; C++)
set_bit[R][C] = ((arr[R][C] & (1 << i)) != 0);
sum += (mul * matrixAllOne(set_bit));
mul *= 2;
}
return sum;
}
// Driver Code
int main()
{
int arr[][n] = { { 9, 7, 4 },
{ 8, 9, 2 },
{ 11, 11, 5 } };
cout << sumAndMatrix(arr);
return 0;
}
Java
// Java program to find sum of Bit-wise AND
// of all submatrices
import java.util.*;
class GFG
{
static int n = 3;
// Function to find prefix-count for
// each row from right to left
static void findPrefixCount(int p_arr[][],
boolean set_bit[][])
{
for (int i = 0; i < n; i++)
{
for (int j = n - 1; j >= 0; j--)
{
if (!set_bit[i][j])
continue;
if (j != n - 1)
p_arr[i][j] += p_arr[i][j + 1];
p_arr[i][j] += (set_bit[i][j]) ? 1 : 0;
}
}
}
static class pair
{
int first,second;
pair(){}
pair(int a, int b)
{
first = a;
second = b;
}
}
// Function to find the number of
// submatrices with all 1s
static int matrixAllOne(boolean set_bit[][])
{
// Array to store required prefix count of 1s from
// right to left for boolean array
int p_arr[][] = new int[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n;j++)
p_arr[i][j] = 0;
findPrefixCount(p_arr, set_bit);
// Variable to store the final answer
int ans = 0;
// For each index of a column, determine the number
// of sub-matrices starting from that index
// and has all 1s
for (int j = 0; j < n; j++)
{
int i = n - 1;
// Stack to store elements and the count
// of the numbers they popped
// First part of pair is value of inserted element
// Second part is count of the number of elements
// pushed before with a greater value
Stack<pair > q = new Stack<pair >();
// variable to store the number of submatrices
// with all 1s
int to_sum = 0;
while (i >= 0)
{
int c = 0;
while (q.size() != 0 &&
q.peek().first > p_arr[i][j])
{
to_sum -= (q.peek().second + 1) *
(q.peek().first - p_arr[i][j]);
c += q.peek().second + 1;
q.pop();
}
to_sum += p_arr[i][j];
ans += to_sum;
q.push(new pair( p_arr[i][j], c ));
i--;
}
}
return ans;
}
// Function to find sum of Bitwise-OR of
// all submatrices
static int sumAndMatrix(int arr[][])
{
int sum = 0;
int mul = 1;
for (int i = 0; i < 30; i++)
{
// matrix to store the status
// of ith bit of each element
// of matrix arr
boolean set_bit[][] = new boolean[n][n];
for (int R = 0; R < n; R++)
for (int C = 0; C < n; C++)
set_bit[R][C] = ((arr[R][C] & (1 << i)) != 0);
sum += (mul * matrixAllOne(set_bit));
mul *= 2;
}
return sum;
}
// Driver Code
public static void main(String args[])
{
int arr[][] = { { 9, 7, 4 },
{ 8, 9, 2 },
{ 11, 11, 5 } };
System.out.println( sumAndMatrix(arr));
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 program to find sum of
# Bitwise-AND of all submatrices
# Function to find prefix-count for
# each row from right to left
def findPrefixCount(p_arr, set_bit):
for i in range(0, n):
for j in range(n - 1, -1, -1):
if not set_bit[i][j]:
continue
if j != n - 1:
p_arr[i][j] += p_arr[i][j + 1]
p_arr[i][j] += int(set_bit[i][j])
# Function to create a boolean matrix
# set_bit which stores ‘1’ at an index
# (R, C) if ith bit of arr[R][C] is set.
def matrixAllOne(set_bit):
# Array to store prefix count of zeros
# from right to left for boolean array
p_arr = [[0 for i in range(n)]
for j in range(n)]
findPrefixCount(p_arr, set_bit)
# Variable to store the final answer
ans = 0
# For each index of a column we
# will try to determine the number
# of sub-matrices starting from
# that index and has all 1s
for j in range(0, n):
i = n - 1
# stack to store elements and the
# count of the numbers they popped
# First part of pair will be the
# value of inserted element.
# Second part will be the count
# of the number of elements pushed
# before with a greater value
q = []
# Variable to store the number
# of submatrices with all 0s
to_sum = 0
while i >= 0:
c = 0
while (len(q) != 0 and
q[-1][0] > p_arr[i][j]):
to_sum -= ((q[-1][1] + 1) *
(q[-1][0] - p_arr[i][j]))
c += q.pop()[1] + 1
to_sum += p_arr[i][j]
ans += to_sum
q.append((p_arr[i][j], c))
i -= 1
# Return the final answer
return ans
# Function to find sum of
# Bitwise-AND of all submatrices
def sumAndMatrix(arr):
Sum, mul = 0, 1
for i in range(0, 30):
# matrix to store the status
# of ith bit of each element
# of matrix arr
set_bit = [[False for i in range(n)]
for j in range(n)]
for R in range(0, n):
for C in range(0, n):
set_bit[R][C] = ((arr[R][C] &
(1 << i)) != 0)
Sum += (mul * matrixAllOne(set_bit))
mul *= 2
return Sum
# Driver Code
if __name__ == "__main__":
n = 3
arr = [[9, 7, 4],
[8, 9, 2],
[11, 11, 5]]
print(sumAndMatrix(arr))
# This code is contributed by Rituraj Jain
C#
// C# program to find sum of Bit-wise AND
// of all submatrices
using System;
using System.Collections.Generic;
class GFG
{
static int n = 3;
// Function to find prefix-count for
// each row from right to left
static void findPrefixCount(int [,]p_arr,
bool [,]set_bit)
{
for (int i = 0; i < n; i++)
{
for (int j = n - 1; j >= 0; j--)
{
if (!set_bit[i, j])
continue;
if (j != n - 1)
p_arr[i, j] += p_arr[i, j + 1];
p_arr[i, j] += (set_bit[i, j]) ? 1 : 0;
}
}
}
public class pair
{
public int first,second;
public pair(){}
public pair(int a, int b)
{
first = a;
second = b;
}
}
// Function to find the number of
// submatrices with all 1s
static int matrixAllOne(bool [,]set_bit)
{
// Array to store required prefix count of 1s from
// right to left for boolean array
int [,]p_arr = new int[n, n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n;j++)
p_arr[i, j] = 0;
findPrefixCount(p_arr, set_bit);
// Variable to store the final answer
int ans = 0;
// For each index of a column, determine the number
// of sub-matrices starting from that index
// and has all 1s
for (int j = 0; j < n; j++)
{
int i = n - 1;
// Stack to store elements and the count
// of the numbers they popped
// First part of pair is value of inserted element
// Second part is count of the number of elements
// pushed before with a greater value
Stack<pair > q = new Stack<pair >();
// variable to store the number of submatrices
// with all 1s
int to_sum = 0;
while (i >= 0)
{
int c = 0;
while (q.Count != 0 &&
q.Peek().first > p_arr[i,j])
{
to_sum -= (q.Peek().second + 1) *
(q.Peek().first - p_arr[i,j]);
c += q.Peek().second + 1;
q.Pop();
}
to_sum += p_arr[i,j];
ans += to_sum;
q.Push(new pair( p_arr[i,j], c ));
i--;
}
}
return ans;
}
// Function to find sum of Bitwise-OR of
// all submatrices
static int sumAndMatrix(int [,]arr)
{
int sum = 0;
int mul = 1;
for (int i = 0; i < 30; i++)
{
// matrix to store the status
// of ith bit of each element
// of matrix arr
bool [,]set_bit = new bool[n,n];
for (int R = 0; R < n; R++)
for (int C = 0; C < n; C++)
set_bit[R, C] = ((arr[R, C] & (1 << i)) != 0);
sum += (mul * matrixAllOne(set_bit));
mul *= 2;
}
return sum;
}
// Driver Code
public static void Main(String []args)
{
int [,]arr = { { 9, 7, 4 },
{ 8, 9, 2 },
{ 11, 11, 5 } };
Console.WriteLine(sumAndMatrix(arr));
}
}
// This code contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to find sum of Bit-wise AND
// of all submatrices
var n = 3;
// Function to find prefix-count for each row
// from right to left
function findPrefixCount(p_arr, set_bit)
{
for (var i = 0; i < n; i++) {
for (var j = n - 1; j >= 0; j--) {
if (!set_bit[i][j])
continue;
if (j != n - 1)
p_arr[i][j] += p_arr[i][j + 1];
p_arr[i][j] += set_bit[i][j];
}
}
}
// Function to find the number of submatrices
// with all 1s
function matrixAllOne(set_bit)
{
// Array to store required prefix count of 1s from
// right to left for boolean array
var p_arr = Array.from(Array(n), ()=> Array(n).fill(0));
findPrefixCount(p_arr, set_bit);
// Variable to store the final answer
var ans = 0;
// For each index of a column, determine the number
// of sub-matrices starting from that index
// and has all 1s
for (var j = 0; j < n; j++) {
var i = n - 1;
// Stack to store elements and the count
// of the numbers they popped
// First part of pair is value of inserted element
// Second part is count of the number of elements
// pushed before with a greater value
var q = [];
// variable to store the number of submatrices
// with all 1s
var to_sum = 0;
while (i >= 0) {
var c = 0;
while (q.length != 0 && q[q.length - 1][0] > p_arr[i][j]) {
to_sum -= (q[q.length - 1][1] + 1) * (q[q.length - 1][0] - p_arr[i][j]);
c += q[q.length - 1][1] + 1;
q.pop();
}
to_sum += p_arr[i][j];
ans += to_sum;
q.push([p_arr[i][j], c ]);
i--;
}
}
return ans;
}
// Function to find the sum of Bitwise-AND
// of all submatrices
function sumAndMatrix(arr)
{
var sum = 0;
var mul = 1;
for (var i = 0; i < 30; i++) {
// matrix to store the status
// of ith bit of each element
// of matrix arr
var set_bit = Array.from(Array(n), ()=> Array(n));
for (var R = 0; R < n; R++)
for (var C = 0; C < n; C++)
set_bit[R][C] = ((arr[R][C] & (1 << i)) != 0);
sum += (mul * matrixAllOne(set_bit));
mul *= 2;
}
return sum;
}
// Driver Code
var arr = [ [ 9, 7, 4 ],
[ 8, 9, 2 ],
[ 11, 11, 5 ] ];
document.write( sumAndMatrix(arr));
</script>
Time Complexity: O(N*N), as we are using nested loops for traversing the matrix.
Auxiliary Space: O(N*N), as we are using any extra space.
Similar Reads
Sum of Bitwise-OR of all Submatrices
Given a NxN matrix, the task is to find the sum of bit-wise OR of all of its rectangular sub-matrices.Examples: Input : arr[][] = {{1, 0, 0}, {0, 0, 0}, {0, 0, 0}} Output : 9 Explanation: All the submatrices starting from the index (0, 0) will have OR value as 1. Thus, ans = 9 Input : arr[][] = {{9,
14 min read
Sum of bitwise AND of all subarrays
Given an array consisting of N positive integers, find the sum of bit-wise and of all possible sub-arrays of the array. Examples: Input : arr[] = {1, 5, 8} Output : 15 Bit-wise AND of {1} = 1 Bit-wise AND of {1, 5} = 1 Bit-wise AND of {1, 5, 8} = 0 Bit-wise AND of {5} = 5 Bit-wise AND of {5, 8} = 0
8 min read
Sum of bitwise OR of all subarrays
Given an array of positive integers, find the total sum after performing the bit wise OR operation on all the sub arrays of a given array. Examples: Input : 1 2 3 4 5 Output : 71 Input : 6 5 4 3 2 Output : 84 First initialize the two variable sum=0, sum1=0, variable sum will store the total sum and,
5 min read
Sum of all Submatrices of a Given Matrix
Given a n * n 2D matrix, the task to find the sum of all the submatrices.Examples: Input : mat[][] = [[1, 1], [1, 1]];Output : 16Explanation: Number of sub-matrices with 1 elements = 4Number of sub-matrices with 2 elements = 4Number of sub-matrices with 3 elements = 0Number of sub-matrices with 4 el
9 min read
Bitwise OR of sum of all subsequences of an array
Given an array arr[] of length N, the task is to find the Bitwise OR of the sum of all possible subsequences from the given array. Examples: Input: arr[] = {4, 2, 5}Output: 15Explanation: All subsequences from the given array and their corresponding sums:{4} - 4{2} - 2{5} - 5{4, 2} - 6{4, 5} - 9{2,
6 min read
Sum of Bitwise AND of all unordered triplets of an array
Given an array arr[] consisting of N positive integers, the task is to find the sum of Bitwise AND of all possible triplets (arr[i], arr[j], arr[k]) such that i < j < k. Examples: Input: arr[] = {3, 5, 4, 7}Output: 5Explanation: Sum of Bitwise AND of all possible triplets = (3 & 5 & 4)
10 min read
Sum of Bitwise And of all pairs in a given array
Given an array "arr[0..n-1]" of integers, calculate sum of "arr[i] & arr[j]" for all the pairs in the given where i < j. Here & is bitwise AND operator. Expected time complexity is O(n). Examples : Input: arr[] = {5, 10, 15} Output: 15 Required Value = (5 & 10) + (5 & 15) + (10
13 min read
Sum of bitwise AND of all possible subsets of given set
Given an array, we need to calculate the Sum of Bit-wise AND of all possible subsets of the given array. Examples: Input : 1 2 3 Output : 9 For [1, 2, 3], all possible subsets are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3} Bitwise AND of these subsets are, 1 + 2 + 3 + 0 + 1 + 2 + 0 = 9. So, th
7 min read
Queries for Sum of Bitwise AND of all Subarrays in a Range
Given an array arr[] of size N, the task is to answer a set of Q queries, each in the format of queries[i][0] and queries[i][1]. For each queries[i], find the sum of Bitwise AND of all subarrays whose elements lie in the range [queries[i][0], queries[i][1]]. Examples: Input: N = 3, arr[] = {1, 0, 2}
12 min read
Number of submatrices with all 1s
Given an N*N matrix containing only 0s and 1s, the task is to count the number of submatrices containing all 1s. Examples: Input : arr[][] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}} Output : 36 Explanation: All the possible submatrices will have only 1s. Since, there are 36 submatrices in total, ans = 36 I
12 min read