Check if all substrings of length K of a Binary String has equal count of 0s and 1s - GeeksforGeeks

17 May, 2021
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 2 has equal number of 0s and 1s, the answer is Yes.
Input: S = “101011”, K = 4Output: NoExplanation:Since substring “1011” has unequal count of 0s and 1s, the answer is No..
Naive Approach: The simplest approach to solve the problem is to generate all substrings of length K and check it if it contains an equal count of 1s and 0s or not. 
Time Complexity: O(N2) Auxiliary Space: O(1)
Efficient Approach: The main observation for optimizing the above approach is, for the string S to have an equal count of 0 and 1 in substrings of length K, S[i] must be equal to S[i + k]. Follow the steps below to solve the problem:
Traverse the string and for every ith character, check if S[i] = S[j] where (i == (j % k))
If found to be false at any instant, then print “No”.
Otherwise, check the first substring of length K and if it contains an equal count of 1s and 0s or not. If found to be true, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Function to check if the substring// of length K has equal 0 and 1int check(string& s, int k){    int n = s.size();     // Traverse the string    for (int i = 0; i < k; i++) {        for (int j = i; j < n; j += k) {             // Check if every K-th character            // is the same or not            if (s[i] != s[j])                return false;        }    }    int c = 0;     // Traverse substring of length K    for (int i = 0; i < k; i++) {         // If current character is 0        if (s[i] == '0')             // Increment count            c++;         // Otherwise        else             // Decrement count            c--;    }     // Check for equal 0s and 1s    if (c == 0)        return true;    else        return false;} // Driver codeint main(){    string s = "101010";    int k = 2;     if (check(s, k))        cout << "Yes" << endl;    else        cout << "No" << endl;     return 0;}
// Java program for// the above approachimport java.util.*;class GFG{ // Function to check if the substring// of length K has equal 0 and 1static boolean check(String s, int k){  int n = s.length();   // Traverse the String  for (int i = 0; i < k; i++)  {    for (int j = i; j < n; j += k)    {      // Check if every K-th character      // is the same or not      if (s.charAt(i) != s.charAt(j))        return false;    }  }  int c = 0;   // Traverse subString of length K  for (int i = 0; i < k; i++)  {    // If current character is 0    if (s.charAt(i) == '0')       // Increment count      c++;     // Otherwise    else       // Decrement count      c--;  }   // Check for equal 0s and 1s  if (c == 0)    return true;  else    return false;} // Driver codepublic static void main(String[] args){  String s = "101010";  int k = 2;   if (check(s, k))    System.out.print("Yes" + "\n");  else    System.out.print("No" + "\n");}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach  # Function to check if the substring# of length K has equal 0 and 1def check(s, k):         n = len(s)      # Traverse the string    for i in range(k):        for j in range(i, n, k):              # Check if every K-th character            # is the same or not            if (s[i] != s[j]):                return False                     c = 0      # Traverse substring of length K    for i in range(k):          # If current character is 0        if (s[i] == '0'):              # Increment count            c += 1          # Otherwise        else:                         # Decrement count            c -= 1                 # Check for equal 0s and 1s    if (c == 0):        return True    else:        return False # Driver codes = "101010"k = 2  if (check(s, k) != 0):    print("Yes")else:    print("No")  # This code is contributed by sanjoy_62
// C# program for// the above approachusing System;class GFG{ // Function to check if the substring// of length K has equal 0 and 1static bool check(String s, int k){  int n = s.Length;   // Traverse the String  for (int i = 0; i < k; i++)  {    for (int j = i; j < n; j += k)    {      // Check if every K-th character      // is the same or not      if (s[i] != s[j])        return false;    }  }  int c = 0;   // Traverse subString of length K  for (int i = 0; i < k; i++)  {    // If current character is 0    if (s[i] == '0')       // Increment count      c++;     // Otherwise    else       // Decrement count      c--;  }   // Check for equal 0s and 1s  if (c == 0)    return true;  else    return false;} // Driver codepublic static void Main(String[] args){  String s = "101010";  int k = 2;   if (check(s, k))    Console.Write("Yes" + "\n");  else    Console.Write("No" + "\n");}} // This code is contributed by Rajput-Ji
<script>// javascript program for the// above approach // Function to check if the substring// of length K has equal 0 and 1function check(s, k){  let n = s.length;    // Traverse the String  for (let i = 0; i < k; i++)  {    for (let j = i; j < n; j += k)    {      // Check if every K-th character      // is the same or not      if (s[i] != s[j])        return false;    }  }  let c = 0;    // Traverse subString of length K  for (let i = 0; i < k; i++)  {    // If current character is 0    if (s[i]== '0')        // Increment count      c++;      // Otherwise    else        // Decrement count      c--;  }    // Check for equal 0s and 1s  if (c == 0)    return true;  else    return false;}  // Driver Code      let s = "101010";  let k = 2;    if (check(s, k))    document.write("Yes" + "<br/>");  else    document.write("No"); // This code is contributed by target_2.</script>
Yes
 
Time Complexity: O(N)Auxiliary Space: O(1) 
29AjayKumar
Rajput-Ji
sanjoy_62
target_2
frequency-counting
substring
Greedy
Pattern Searching
Searching
Strings
Searching
Strings
Greedy
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program for First Fit algorithm in Memory Management
Program for Best Fit algorithm in Memory Management
Optimal Page Replacement Algorithm
Program for Worst Fit algorithm in Memory Management
Max Flow Problem Introduction
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching