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 have any set bits in it, so ans is 0.

Naive Approach:



  1. Generate all substring of size K.
  2. Find maximum of count of set bits in all substrings.

Time Complexity: O( N2).
Auxillary Space: O(1).

Efficient Approach: The problem can be solved using Sliding window technique.

  1. Take maxcount variable to store maximum count of set bit and Count variable to store count set bit of current window.
  2. Traverse string from 1 to K and calculate the count of set bits and store as maxcount.
  3. Traverse string from K + 1 to length of the string.
  4. At every iteration, decrease count if (K – i)th bit is set. Increase count if ith bit is set. Compare and update maxcount.
  5. After complete array traversal, finally return maxcount.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the maximum
// set bits in a substring of size K
#include<bits/stdc++.h>
using namespace std;
  
// Function that find Maximum number
// of set bit appears in a substring
// of size K.
int maxSetBitCount(string s, int k)
{
    int maxCount = 0, n = s.length();
    int count = 0;
  
    // Traverse string 1 to k
    for(int i = 0; i < k; i++) 
    {
          
       // Incerement count if
       // character is set bit
       if (s[i] == '1')
           count++;
    }
    maxCount = count;
  
    // Traverse string k+1
    // to length of string
    for(int i = k; i < n; i++)
    {
         
       // Remove the contribution of the
       // (i - k)th character which is no
       // longer in the window
       if (s[i - k] == '1')
           count--;
         
       // Add the contribution of
       // the current character
       if (s[i] == '1')
           count++;
             
       // Update maxCount at for
       // each window of size k
       maxCount = max(maxCount, count);
    }
      
    // Return maxCount
    return maxCount;
}
  
// Driver code
int main()
{
    string s = "100111010";
    int k = 3;
  
    cout << (maxSetBitCount(s, k));
    return 0;
}
  
// This code is contributed by Rajput-Ji

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the maximum
// set bits in a substring of size K
import java.util.*;
  
class GFG {
  
    // Function that find Maximum number
    // of set bit appears in a substring
    // of size K.
    static int maxSetBitCount(String s, int k)
    {
  
        int maxCount = 0, n = s.length();
        int count = 0;
  
        // Traverse string 1 to k
        for (int i = 0; i < k; i++) {
            // Incerement count if
            // character is set bit
            if (s.charAt(i) == '1')
                count++;
        }
  
        maxCount = count;
  
        // Traverse string k+1
        // to length of string
        for (int i = k; i < n; i++) {
  
            // remove the contribution of the
            // (i - k)th character which is no
            // longer in the window
            if (s.charAt(i - k) == '1')
                count--;
  
            // add the contribution of
            // the current character
            if (s.charAt(i) == '1')
                count++;
  
            // update maxCount at for
            // each window of size k
            maxCount = Math.max(maxCount, count);
        }
  
        // return maxCount
        return maxCount;
    }
    // Driver Program
    public static void main(String[] args)
    {
        String s = "100111010";
        int k = 3;
  
        System.out.println(maxSetBitCount(s, k));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find the maximum
# set bits in a substring of size K
  
# Function that find Maximum number
# of set bit appears in a substring
# of size K.
def maxSetBitCount(s, k):
  
    maxCount = 0
    n = len(s)
    count = 0
  
    # Traverse string 1 to k
    for i in range(k):
          
        # Incerement count if
        # character is set bit
        if (s[i] == '1'):
            count += 1
  
    maxCount = count
  
    # Traverse string k+1
    # to length of string
    for i in range(k, n):
  
        # Remove the contribution of the
        # (i - k)th character which is no
        # longer in the window
        if (s[i - k] == '1'):
            count -= 1
  
        # Add the contribution of
        # the current character
        if (s[i] == '1'):
            count += 1
  
        # Update maxCount at for
        # each window of size k
        maxCount = max(maxCount, count)
  
    # Return maxCount
    return maxCount
  
  
# Driver code
if __name__ == '__main__':
      
    s = "100111010"
    k = 3
  
    print(maxSetBitCount(s, k))
      
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the maximum
// set bits in a substring of size K
using System;
class GFG {
  
// Function that find Maximum number
// of set bit appears in a substring
// of size K.
static int maxSetBitCount(string s, int k)
{
  
    int maxCount = 0, n = s.Length;
    int count = 0;
  
    // Traverse string 1 to k
    for (int i = 0; i < k; i++) 
    {
        // Incerement count if
        // character is set bit
        if (s[i] == '1')
            count++;
    }
  
    maxCount = count;
  
    // Traverse string k+1
    // to length of string
    for (int i = k; i < n; i++) 
    {
  
        // remove the contribution of the
        // (i - k)th character which is no
        // longer in the window
        if (s[i - k] == '1')
            count--;
  
        // add the contribution of
        // the current character
        if (s[i] == '1')
            count++;
  
        // update maxCount at for
        // each window of size k
        maxCount = Math.Max(maxCount, count);
    }
  
    // return maxCount
    return maxCount;
}
// Driver Program
public static void Main()
{
    string s = "100111010";
    int k = 3;
  
    Console.Write(maxSetBitCount(s, k));
}
}
  
// This code is contributed by Code_Mech

chevron_right


Output:

3

Time Complexity: O(N).
Auxiliary Space: O(1).

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.