Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Check if any pair of consecutive 1s can be separated by at most M 0s by circular rotation of a Binary String

  • Last Updated : 22 Apr, 2021

Given a binary string S of length N and a positive integer M, the task is to check if it is possible to rotate the string circularly any number of times such that any pair of consecutive 1s are separated by at most M 0s. If it is possible, then print “Yes”. Otherwise, print “No”.

Examples:

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: S = “101001”, M = 1
Output: Yes
Explanation: Right shift the characters of the given string by 1 place. Therefore, the string S modifies to “110100”, leaving all pair of consecutive 1s separated by at most M(= 1) 0s.



Input: S = 1001001, M = 1
Output: No

Approach: The given problem can be solved based on the observation that if there are more than 1 pair of adjacent 1s having more than M number of 0s between them, then it is not possible to satisfy the given condition, because only such pair can be handled by rotating the string in such a way that all the 0s in between them are at the end. 
Follow the steps below to solve the problem:

  • Initialize a vector, say V, to store the indices of all 1s in the given string S.
  • Initialize a variable, say, count, to store the number of pairs of 1s having more than M 0s between them.
  • Traverse the given string S and store all indices of ‘1’ in the vector V.
  • Traverse the vector V, starting from index 1 using a variable, say i, and perform the following steps: 
    • Store the number of 0s between indices V[i] and V[i – 1] in the string S in a variable T as (V[i] – V[i – 1] – 1).
    • If the value of T is greater than M, then increment the value of count by 1.
  • If the number of 0s between the first and last occurrence of ‘1’ is greater than M, then increment the value of count by 1.
  • After completing the above steps, if the value of count is at most 1, then print Yes. Otherwise, print “No”.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if any pair of
// consecutive 1s can be separated by at
// most M 0s by circular rotation of string S
void rotateString(int n, int m, string s)
{
    // Stores the indices of all 1s
    vector<int> v;
 
    // Store the number of pairs
    // separated by at least M 0s
    int cnt = 0;
 
    // Traverse the string
    for (int i = 0; i < n; i++) {
 
        if (s[i] == '1') {
 
            // Store the current index
            v.push_back(i);
        }
    }
 
    // Traverse the array containing indices
    for (int i = 1; i < (int)v.size(); i++) {
 
        // If the number of 0s > M,
        // then increment cnt by 1
        if ((v[i] - v[i - 1] - 1) > m) {
 
            // Increment cnt
            cnt++;
        }
    }
 
    // Check if at least M '0's lie between
    // the first and last occurrence of '1'
    if (v.size() >= 2
        && (n - (v.back() - v[0]) - 1) > m) {
 
        // Increment cnt
        cnt++;
    }
 
    // If the value of cnt <= 1, then
    // rotation of string is possible
    if (cnt <= 1) {
        cout << "Yes";
    }
 
    // Otherwise
    else {
        cout << "No";
    }
}
 
// Driver Code
int main()
{
    string S = "101001";
    int M = 1;
    int N = S.size();
    rotateString(N, M, S);
 
    return 0;
}

Java




// Java program for the above approach
class GFG{
     
// Function to check if any pair of
// consecutive 1s can be separated by at
// most M 0s by circular rotation of string S
static void rotateString(int n, int m, String s)
{
     
    // Stores the indices of all 1s
    int v[] = new int[n];
 
    // Store the number of pairs
    // separated by at least M 0s
    int cnt = 0;
    int j = 0;
     
    // Traverse the string
    for(int i = 0; i < n; i++)
    {
        if (s.charAt(i) == '1')
        {
             
            // Store the current index
            v[j] = i;
            j += 1;
        }
    }
 
    // Traverse the array containing indices
    for(int i = 1; i < j; i++)
    {
         
        // If the number of 0s > M,
        // then increment cnt by 1
        if ((v[i] - v[i - 1] - 1) > m)
        {
             
            // Increment cnt
            cnt++;
        }
    }
 
    // Check if at least M '0's lie between
    // the first and last occurrence of '1'
    if (j >= 2 && (n - (v[j - 1] - v[0]) - 1) > m)
    {
         
        // Increment cnt
        cnt++;
    }
 
    // If the value of cnt <= 1, then
    // rotation of string is possible
    if (cnt <= 1)
    {
        System.out.print("Yes");
    }
 
    // Otherwise
    else
    {
        System.out.print("No");
    }
}
 
// Driver Code
public static void main (String[] args)
{
    String S = "101001";
    int M = 1;
    int N = S.length();
     
    rotateString(N, M, S);
}
}
 
// This code is contributed by AnkThon

Python3




# Python3 program for the above approach
 
# Function to check if any pair of
# consecutive 1s can be separated by at
# most M 0s by circular rotation of string S
def rotateString(n, m, s):
     
    # Stores the indices of all 1s
    v = []
 
    # Store the number of pairs
    # separated by at least M 0s
    cnt = 0
 
    # Traverse the string
    for i in range(n):
        if (s[i] == '1'):
             
            # Store the current index
            v.append(i)
 
    # Traverse the array containing indices
    for i in range(1, len(v)):
         
        # If the number of 0s > M,
        # then increment cnt by 1
        if ((v[i] - v[i - 1] - 1) > m):
 
            # Increment cnt
            cnt += 1
 
    # Check if at least M '0's lie between
    # the first and last occurrence of '1'
    if (len(v) >= 2 and
       (n - (v[-1] - v[0]) - 1) > m):
         
        # Increment cnt
        cnt += 1
 
    # If the value of cnt <= 1, then
    # rotation of string is possible
    if (cnt <= 1):
        print("Yes")
         
    # Otherwise
    else:
        print("No")
 
# Driver Code
if __name__ == '__main__':
     
    S = "101001"
    M = 1
    N = len(S)
     
    rotateString(N, M, S)
 
# This code is contributed by mohit kumar 29

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
   
// Function to check if any pair of
// consecutive 1s can be separated by at
// most M 0s by circular rotation of string S
static void rotateString(int n, int m, string s)
{
     
    // Stores the indices of all 1s
    List<int> v = new List<int>();
 
    // Store the number of pairs
    // separated by at least M 0s
    int cnt = 0;
 
    // Traverse the string
    for(int i = 0; i < n; i++)
    {
        if (s[i] == '1')
        {
             
            // Store the current index
            v.Add(i);
        }
    }
 
    // Traverse the array containing indices
    for(int i = 1; i < v.Count; i++)
    {
         
        // If the number of 0s > M,
        // then increment cnt by 1
        if ((v[i] - v[i - 1] - 1) > m)
        {
             
            // Increment cnt
            cnt++;
        }
    }
 
    // Check if at least M '0's lie between
    // the first and last occurrence of '1'
    if (v.Count >= 2 &&
       (n - (v[v.Count - 1] - v[0]) - 1) > m)
    {
 
        // Increment cnt
        cnt++;
    }
 
    // If the value of cnt <= 1, then
    // rotation of string is possible
    if (cnt <= 1)
    {
        Console.Write("Yes");
    }
 
    // Otherwise
    else
    {
        Console.Write("No");
    }
}
 
// Driver Code
public static void Main()
{
    string S = "101001";
    int M = 1;
    int N = S.Length;
     
    rotateString(N, M, S);
}
}
 
// This code is contributed by ipg2016107

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to check if any pair of
// consecutive 1s can be separated by at
// most M 0s by circular rotation of string S
 
function rotateString(n, m, s)
{
    // Stores the indices of all 1s
    var v = [];
 
    // Store the number of pairs
    // separated by at least M 0s
    var cnt = 0;
     var i;
    // Traverse the string
    for (i = 0; i < n; i++) {
 
        if (s[i] == '1') {
 
            // Store the current index
            v.push(i);
        }
    }
 
    // Traverse the array containing indices
    for (i = 1; i < v.length; i++) {
 
        // If the number of 0s > M,
        // then increment cnt by 1
        if ((v[i] - v[i - 1] - 1) > m) {
 
            // Increment cnt
            cnt++;
        }
    }
 
    // Check if at least M '0's lie between
    // the first and last occurrence of '1'
    if (v.length >= 2
        && (n - (v[v.length-1] - v[0]) - 1) > m) {
 
        // Increment cnt
        cnt++;
    }
 
    // If the value of cnt <= 1, then
    // rotation of string is possible
    if (cnt <= 1) {
       document.write("Yes");
    }
 
    // Otherwise
    else {
        document.write("No");
    }
}
 
// Driver Code
    var S = "101001";
    var M = 1;
    var N = S.length;
    rotateString(N, M, S);
 
</script>
Output: 
Yes

 

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :