The Wayback Machine - https://web.archive.org/web/20220204033307/https://www.geeksforgeeks.org/count-of-setbits-in-bitwise-or-of-all-k-length-substrings-of-given-binary-string/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count of setbits in bitwise OR of all K length substrings of given Binary String

  • Last Updated : 03 Feb, 2022

Given a binary string str of length N, the task is to find the number of setbits in the bitwise OR of all the K length substrings of string str.

Examples:

Input: N = 4, K = 3, str = “1111”
Output: 3
Explanation: All 3-sized substrings of S are:
“111” and “111”. The OR of these strings is “111”. 
Therefore the number of 1 bits is 3.

Input: N = 4, K = 4, str = “0110”
Output: 2
Explanation: All 4-sized substrings of S are “0110”.
The OR of these strings is “0110”. 
Therefore the number of 1 bits is 2.

 

Approach: The solution of the problem is based on the concept of Sliding window Technique. Follow the steps mentioned below:

  • Use sliding window technique and find all substrings of size K.
  • Store all substring of size K.(here vector of strings is used).
  • Do OR of all strings.
  • Count the number of setbits and return.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to make OR two string
string ORing(string a, string b)
{
    string ans = "";
    int n = a.size();
    for (int i = 0; i < n; i++) {
        if (a[i] == '1' || b[i] == '1')
            ans += "1";
        else
            ans += "0";
    }
    return ans;
}
  
// Function to check the setbits
// in OR of all K size substring
int solve(string str, int N, int K)
{
    // Making vector to store answer
    vector<string> v1;
    int windowsize = K;
    int i = 0;
    int j = 0;
    string temp = "";
  
    // Using sliding window technique
    while (j < N) {
        temp.push_back(str[j]);
        if (j - i + 1 < windowsize) {
            j++;
        }
        else {
            v1.push_back(temp);
            reverse(temp.begin(), temp.end());
            temp.pop_back();
            reverse(temp.begin(), temp.end());
            i++;
            j++;
        }
    }
  
    // OR of all strings which
    // are present in the vector
    string a = v1[0];
    for (int i = 1; i < v1.size(); i++) {
        a = ORing(a, v1[i]);
    }
  
    // Counting number of set bit
    int count = 0;
    for (int i = 0; i < a.size(); i++) {
        if (a[i] == '1') {
            count++;
        }
    }
    return count;
}
  
// Driver code
int main()
{
    int N = 4;
    int K = 3;
    string str = "1111";
  
    // Calling function
    cout << solve(str, N, K);
    return 0;
}
Output
3

Time Complexity: O(N * N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!