Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Last Updated : 08 Mar, 2022
View Discussion
Improve Article
Save Article

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;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG {
 
  // Function to make OR two String
  static String ORing(String a, String b) {
    String ans = "";
    int n = a.length();
    for (int i = 0; i < n; i++) {
      if (a.charAt(i) == '1' || b.charAt(i) == '1')
        ans += "1";
      else
        ans += "0";
    }
    return ans;
  }
 
  static String reverse(String input) {
    char[] a = input.toCharArray();
    int l, r = a.length - 1;
    for (l = 0; l < r; l++, r--) {
      char temp = a[l];
      a[l] = a[r];
      a[r] = temp;
    }
    return String.valueOf(a);
  }
 
  // Function to check the setbits
  // in OR of all K size subString
  static int solve(String str, int N, int K)
  {
 
    // Making vector to store answer
    Vector<String> v1 = new Vector<>();
    int windowsize = K;
    int i = 0;
    int j = 0;
    String temp = "";
 
    // Using sliding window technique
    while (j < N) {
      temp += (str.charAt(j));
      if (j - i + 1 < windowsize) {
        j++;
      } else {
        v1.add(temp);
        temp = reverse(temp);
        temp = temp.substring(0, temp.length() - 1);
        temp = reverse(temp);
        i++;
        j++;
      }
    }
 
    // OR of all Strings which
    // are present in the vector
    String a = v1.get(0);
    for (i = 1; i < v1.size(); i++) {
      a = ORing(a, v1.get(i));
    }
 
    // Counting number of set bit
    int count = 0;
    for (i = 0; i < a.length(); i++) {
      if (a.charAt(i) == '1') {
        count++;
      }
    }
    return count;
  }
 
  // Driver code
  public static void main(String[] args) {
    int N = 4;
    int K = 3;
    String str = "1111";
 
    // Calling function
    System.out.print(solve(str, N, K));
  }
}
 
// This code is contributed by Rajput-Ji

Python3




# Python code for the above approach
 
# Function to make OR two string
def ORing(a, b):
    ans = "";
    n = len(a)
    for i in range(n):
        if (a[i] == '1' or b[i] == '1'):
            ans += '1';
        else:
            ans += '0';
     
    return list(ans)
 
# Function to check the setbits
# in OR of all K size substring
def solve(str, N, K):
   
    # Making vector to store answer
    v1 = [];
    windowsize = K;
    i = 0;
    j = 0;
    temp = [];
 
    # Using sliding window technique
    while (j < N):
        temp.append(str[j]);
        if (j - i + 1 < windowsize):
            j += 1
        else:
            v1.append(''.join(temp));
            temp.pop(0)
            i += 1
            j += 1
         
    # OR of all strings which
    # are present in the vector
    a = v1[0];
    for i in range(1, len(v1)):
        a = ORing(a, v1[i]);
     
    # Counting number of set bit
    count = 0;
    for i in range(len(a)):
        if (a[i] == '1'):
            count = count + 1;
         
    return count;
 
# Driver code
N = 4;
 
K = 3;
str = "1111";
 
# Calling function
print(solve(str, N, K));
 
# This code is contributed by Saurabh Jaiswal

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
 
  // Function to make OR two String
  static String ORing(String a, String b) {
    String ans = "";
    int n = a.Length;
    for (int i = 0; i < n; i++) {
      if (a[i] == '1' || b[i] == '1')
        ans += "1";
      else
        ans += "0";
    }
    return ans;
  }
 
  static String reverse(String input) {
    char[] a = input.ToCharArray();
    int l, r = a.Length - 1;
    for (l = 0; l < r; l++, r--) {
      char temp = a[l];
      a[l] = a[r];
      a[r] = temp;
    }
    return String.Join("",a);
  }
 
  // Function to check the setbits
  // in OR of all K size subString
  static int solve(String str, int N, int K)
  {
 
    // Making vector to store answer
    List<String> v1 = new List<String>();
    int windowsize = K;
    int i = 0;
    int j = 0;
    String temp = "";
 
    // Using sliding window technique
    while (j < N) {
      temp += (str[j]);
      if (j - i + 1 < windowsize) {
        j++;
      } else {
        v1.Add(temp);
        temp = reverse(temp);
        temp = temp.Substring(0, temp.Length - 1);
        temp = reverse(temp);
        i++;
        j++;
      }
    }
 
    // OR of all Strings which
    // are present in the vector
    String a = v1[0];
    for (i = 1; i < v1.Count; i++) {
      a = ORing(a, v1[i]);
    }
 
    // Counting number of set bit
    int count = 0;
    for (i = 0; i < a.Length; i++) {
      if (a[i] == '1') {
        count++;
      }
    }
    return count;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int N = 4;
    int K = 3;
    String str = "1111";
 
    // Calling function
    Console.Write(solve(str, N, K));
  }
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to make OR two string
       function ORing(a, b) {
           let ans = "";
           let n = a.length;
           for (let i = 0; i < n; i++) {
               if (a[i] == '1' || b[i] == '1')
                   ans += '1';
               else
                   ans += '0';
           }
           return ans.split('');
       }
 
       // Function to check the setbits
       // in OR of all K size substring
       function solve(str, N, K) {
           // Making vector to store answer
           let v1 = [];
           let windowsize = K;
           let i = 0;
           let j = 0;
           let temp = [];
 
           // Using sliding window technique
           while (j < N) {
               temp.push(str[j]);
               if (j - i + 1 < windowsize) {
                   j++;
               }
               else {
                   v1.push(temp.join(''));
                   temp.shift()
                   i++;
                   j++;
               }
           }
 
           // OR of all strings which
           // are present in the vector
           let a = v1[0];
           for (let i = 1; i < v1.length; i++) {
               a = ORing(a, v1[i]);
           }
 
           // Counting number of set bit
           let count = 0;
           for (let i = 0; i < a.length; i++) {
               if (a[i] == '1') {
                   count = count + 1;
               }
           }
           return count;
       }
 
       // Driver code
       let N = 4;
       let K = 3;
       let str = "1111";
 
       // Calling function
       document.write(solve(str, N, K));
 
      // This code is contributed by Potta Lokesh
   </script>

 
 

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!