Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Maximum number of set bits count in a K-size substring of a Binary String
Next article icon

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

Last Updated : 08 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

 



Next Article
Maximum number of set bits count in a K-size substring of a Binary String
author
sauarbhyadav
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Mathematical
  • Strings
  • binary-string
  • Bitwise-OR
  • setBitCount
  • sliding-window
Practice Tags :
  • Bit Magic
  • Mathematical
  • sliding-window
  • Strings

Similar Reads

  • Count of substrings of a binary string containing K ones
    Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones. Examples: Input : s = “10010” K = 1 Output : 9 The 9 substrings containing one 1 are, “1”, “10”, “100”, “001”, “01”, “1”, “10”, “0010” and “010”Recommen
    7 min read
  • Count of K length subarrays containing only 1s in given Binary String | Set 2
    Given binary string str, the task is to find the count of K length subarrays containing only 1s. Examples Input: str = "0101000", K=1Output: 2Explanation: 0101000 -> There are 2 subarrays of length 1 containing only 1s. Input: str = "11111001", K=3Output: 3 Approach: The given problem can also be
    4 min read
  • Maximum number of set bits count in a K-size substring of a Binary String
    Given a binary string S of size N and an integer K. The task is to find the maximum number of set bit appears in a substring of size K. Examples: Input: S = "100111010", K = 3 Output: 3 Explanation: The substring "111" contains 3 set bits. Input:S = "0000000", K = 4 Output: 0 Explanation: S doesn't
    10 min read
  • Check if all substrings of length K of a Binary String has equal count of 0s and 1s
    Given a binary string S of length N and an even integer K, the task is to check if all substrings of length K contains an equal number of 0s and 1s. If found to be true, print “Yes”. Otherwise, print “No”. Examples: Input: S = "101010", K = 2Output: YesExplanation:Since all the substrings of length
    6 min read
  • Count of K length subarrays containing only 1s in given Binary String
    Given a binary string str, the task is to find the count of K length subarrays containing only 1s. Examples: Input: str = "0101000", K=1Output: 2Explanation: 0101000 -> There are 2 subarrays with 1 ones Input: str = "11111001", K=3Output: 3 Approach: The task can be solved by keeping track of the
    4 min read
  • Count of substrings of a given Binary string with all characters same
    Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = “011”Output: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
    10 min read
  • Count of binary strings of given length consisting of at least one 1
    Given an integer N, the task is to print the number of binary strings of length N which at least one '1'. Examples: Input: 2 Output: 3 Explanation: "01", "10" and "11" are the possible strings Input: 3 Output: 7 Explanation: "001", "011", "010", "100", "101", "110" and "111" are the possible strings
    3 min read
  • Count of Reverse Bitonic Substrings in a given String
    Given a string S, the task is to count the number of Reverse Bitonic Substrings in the given string. Reverse bitonic substring: A string in which the ASCII values of the characters of the string follow any of the following patterns: Strictly IncreasingStrictly decreasingDecreasing and then increasin
    8 min read
  • Convert to a string that is repetition of a substring of k length
    Given a string, find if it is possible to convert it to a string that is the repetition of a substring with k characters. To convert, we can replace one substring of length k starting at index i (zero-based indexing) such that i is divisible by K, with k characters. Examples: Input: str = "bdac", k
    7 min read
  • Count binary strings of length same as given string after removal of substrings "01" and "00" that consists of at least one '1'
    Given a binary string S, the task is to count total binary strings consisting of at least one '1' of length equal to the length of the given string after repeatedly removing all occurrences of substrings "10" and "00" from the given string. Examples: Input: S = "111"Output: 7Explanation: Since there
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences