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