Given a binary string 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._

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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**countif (K – i)th bit is set. Increasecount** if ith bit is set. Compare and update maxcount.
  5. After complete array traversal, finally return maxcount.

#bit magic #strings #binary-string #setbitcount #sliding-window #substring

Maximum number of set bits count in a K-size substring of a Binary String - GeeksforGeeks
11.75 GEEK