Find all K length subarrays containing only 1s in given Binary String - GeeksforGeeks

29 Dec, 2021
Given a binary string str[], the task is to find all possible K length subarrays containing only 1s and print their starting and ending index.
Examples:
Input: str = “0101000”, K=1Output: 1 13 3Explanation: Substrings at positions 1 and 3 are the substrings with value 1.
Input: str = “11111001”, K=3Output: 0 21 32 4
Approach: The given problem can be solved with the help of the Sliding Window technique. Create a window of size K initially with a count of 1s from range 0 to K-1. Then traverse the string from index 1 to N-1 and subtract the value of i-1 and add the value of i+K to the current count. If the current count is equal to K, print the value of i and i+k-1 as one of the possible subarrays. Follow the steps below to solve the problem:
Initialize the variable cntOf1s as 0.
Iterate over the range [0, K) using the variable i and perform the following tasks:If s[i] equals 1 then increase the value of cntOf1s by 1.
If s[i] equals 1 then increase the value of cntOf1s by 1.
If cntOf1s equals K then print the current substring as one of the answer.
Iterate over the range [1, N) using the variable i and perform the following tasks:Reduce the value from the left and add from the right to the variable cntOf1s if the characters at that position are 1.If the value of cntOf1s equals K, then print the current substring as the answer.
Reduce the value from the left and add from the right to the variable cntOf1s if the characters at that position are 1.
If the value of cntOf1s equals K, then print the current substring as the answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;  // Function to find all possible// k length subarraysvoid get(string s, int k){    int n = s.length();      int cntOf1s = 0;      // Initial window    for (int i = 0; i < k; i++)        if (s[i] == '1')            cntOf1s++;      if (cntOf1s == k)        cout << 0 << " " << k - 1 << endl;      // Traverse the string    for (int i = 1; i < n; i++) {          // Subtract the value from the left and        // add from the right        cntOf1s = cntOf1s - (s[i - 1] - '0')                  + (s[i + k - 1] - '0');          // Check the condition        if (cntOf1s == k)            cout << i << " " << i + k - 1 << endl;    }}  // Driver Codeint main(){    string str = "0110101110";    int K = 2;    get(str, K);    return 0;}
// Java program for the above approachimport java.util.*;class GFG{  // Function to find all possible// k length subarraysstatic void get(char[] s, int k){    int n = s.length;      int cntOf1s = 0;      // Initial window    for (int i = 0; i < k; i++)        if (s[i] == '1')            cntOf1s++;      if (cntOf1s == k)        System.out.print(0+ " " +  (k - 1 )+"\n");      // Traverse the String    for (int i = 1; i < n && (i + k - 1)<n; i++) {          // Subtract the value from the left and        // add from the right        cntOf1s = cntOf1s - (s[i - 1] - '0')                  + (s[i + k - 1] - '0');          // Check the condition        if (cntOf1s == k)            System.out.print(i+ " " +  (i + k - 1 )+"\n");    }}  // Driver Codepublic static void main(String[] args){    String str = "0110101110";    int K = 2;    get(str.toCharArray(), K);}}  // This code is contributed by 29AjayKumar
# python3 program for the above approach  # Function to find all possible# k length subarraysdef get(s, k):      n = len(s)    cntOf1s = 0      # Initial window    for i in range(0, k):        if (s[i] == '1'):            cntOf1s += 1      if (cntOf1s == k):        print(f"{0} {k - 1}")      # Traverse the string    for i in range(1, n - k + 1):          # Subtract the value from the left and        # add from the right        cntOf1s = cntOf1s - (ord(s[i - 1]) - ord('0')) + \            (ord(s[i + k - 1]) - ord('0'))          # Check the condition        if (cntOf1s == k):            print(f"{i} {i + k - 1}")  # Driver Codeif __name__ == "__main__":      str = "0110101110"    K = 2    get(str, K)  # This code is contributed by rakeshsahni
// C# program for the above approachusing System;class GFG{    // Function to find all possible  // k length subarrays  static void get(char[] s, int k)  {    int n = s.Length;      int cntOf1s = 0;      // Initial window    for (int i = 0; i < k; i++)      if (s[i] == '1')        cntOf1s++;      if (cntOf1s == k)      Console.Write(0 + " " + (k - 1) + "\n");      // Traverse the String    for (int i = 1; i < n && (i + k - 1) < n; i++)    {        // Subtract the value from the left and      // add from the right      cntOf1s = cntOf1s - (s[i - 1] - '0')        + (s[i + k - 1] - '0');        // Check the condition      if (cntOf1s == k)        Console.Write(i + " " + (i + k - 1) + "\n");    }  }    // Driver Code  public static void Main()  {    String str = "0110101110";    int K = 2;    get(str.ToCharArray(), K);  }}  // This code is contributed by Saurabh Jaiswal
<script>      // JavaScript code for the above approach       // Function to find all possible      // k length subarrays      function get(s, k) {          let n = s.length;           let cntOf1s = 0;           // Initial window          for (let i = 0; i < k; i++)              if (s[i] == '1')                  cntOf1s++;           if (cntOf1s == k)              document.write(0 + ' ' + (k - 1) + '<br>');           // Traverse the string          for (let i = 1; i < n; i++) {               // Subtract the value from the left and              // add from the right              cntOf1s = cntOf1s - (s[i - 1].charCodeAt(0) - '0'.charCodeAt(0))                  + (s[i + k - 1].charCodeAt(0) - '0'.charCodeAt(0));               // Check the condition              if (cntOf1s == k)                  document.write(i + ' ' + (i + k - 1) + '<br>');          }      }       // Driver Code      let str = "0110101110";       let K = 2;      get(str, K); // This code is contributed by Potta Lokesh  </script>
  
1 2
6 7
7 8
 
Time Complexity: O(N)Auxiliary Space: O(1)
 
lokeshpotta20
rakeshsahni
29AjayKumar
_saurabh_jaiswal
Algo-Geek 2021
binary-string
subarray
Algo Geek
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find simple moving average | Set-2
Divide given number into two even parts
Check if the given string is valid English word or not
Check if all duplicate elements in the Array are adjacent or not
Count of Palindrome Strings in given Array of strings
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string