Check if a binary string has a 0 between 1s or not | Set 1 (General approach)
Last Updated :
18 Apr, 2023
Given a string of 0 and 1, we need to check that the given string is valid or not. The given string is valid when there is no zero present in between 1’s. For example, 1111, 0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not.
One approach to solving the problem is discussed here, other using Regular expressions is given Set 2
Examples:
Input : 100
Output : VALID
Input : 1110001
Output : NOT VALID
There is 0 between 1s
Input : 00011
Output : VALID
Approach 1 : (Simple Traversal)
Suppose we have a string: 01111011110000 Now take two variables say A and B. run a loop for 0 to length of the string and point A to the first occurrence of 1, after that again run a loop from length of the string to 0and point second variable to the last occurrence of 1.So A = 1 (Position of first ‘1’ is the string) and B = 9 (last occurrence of ‘1’).Now run a loop from A to B and check that ‘0’ is present between 1 or not, if “YES” than set flag to 1 and break the loop, else set flag to 0.In this case flag will set to 1 as the given string is not valid and print “NOT VALID”.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkString(string s)
{
int len = s.length();
int first = s.size() + 1;
for ( int i = 0; i < len; i++) {
if (s[i] == '1' ) {
first = i;
break ;
}
}
int last = 0;
for ( int i = len - 1; i >= 0; i--) {
if (s[i] == '1' ) {
last = i;
break ;
}
}
for ( int i = first; i <= last; i++)
if (s[i] == '0' )
return false ;
return true ;
}
int main()
{
string s = "00011111111100000" ;
checkString(s) ? cout << "VALID\n" : cout << "NOT VALID\n" ;
return 0;
}
|
Java
class Test {
static boolean checkString(String s)
{
int len = s.length();
int first = 0 ;
for ( int i = 0 ; i < len; i++) {
if (s.charAt(i) == '1' ) {
first = i;
break ;
}
}
int last = 0 ;
for ( int i = len - 1 ; i >= 0 ; i--) {
if (s.charAt(i) == '1' ) {
last = i;
break ;
}
}
for ( int i = first; i <= last; i++)
if (s.charAt(i) == '0' )
return false ;
return true ;
}
public static void main(String args[])
{
String s = "00011111111100000" ;
System.out.println(checkString(s) ? "VALID" : "NOT VALID" );
}
}
|
Python
def checkString(s):
Len = len (s)
first = len (s) + 1
for i in range ( Len ):
if (s[i] = = '1' ):
first = i
break
last = 0
for i in range ( Len - 1 ,
- 1 , - 1 ):
if (s[i] = = '1' ):
last = i
break
for i in range (first,
last + 1 ):
if (s[i] = = '0' ):
return False
return True
s = "00011111111100000"
if (checkString(s)):
print ( "VALID" )
else :
print ( "NOT VALID" )
|
C#
using System;
class GFG {
static bool checkString(String s)
{
int len = s.Length;
int first = 0;
for ( int i = 0; i < len; i++) {
if (s[i] == '1' ) {
first = i;
break ;
}
}
int last = 0;
for ( int i = len - 1; i >= 0; i--) {
if (s[i] == '1' ) {
last = i;
break ;
}
}
for ( int i = first; i <= last; i++)
if (s[i] == '0' )
return false ;
return true ;
}
public static void Main()
{
string s = "00011111111100000" ;
Console.WriteLine(checkString(s) ?
"VALID" : "NOT VALID" );
}
}
|
Javascript
<script>
function checkString(s)
{
let len = s.length;
let first = 0;
for (let i = 0; i < len; i++) {
if (s[i] == '1' ) {
first = i;
break ;
}
}
let last = 0;
for (let i = len - 1; i >= 0; i--) {
if (s[i] == '1' ) {
last = i;
break ;
}
}
for (let i = first; i <= last; i++)
if (s[i] == '0' )
return false ;
return true ;
}
let s = "00011111111100000" ;
document.write(checkString(s) ?
"VALID" : "NOT VALID" );
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1) since it is using constant space for variables
Approach 2 : (Using Two Pointers)
Will keep two pointers on the both end of the string and will check whether in the both side ‘1’ is found (track the index with another variable) or not. If in the both sides we find ‘1’ then will run another loop for the inner part using the other two variables, which will again be a part of two pointers algorithm.
Look at the code for better understanding,
C++
#include <bits/stdc++.h>
using namespace std;
bool checkString(string s)
{
int i = 0, j = s.size() - 1;
int si = -1, ei = -1;
while (i <= j) {
if (si == -1 and s[i] == '1' )
si = i;
if (ei == -1 and s[j] == '1' )
ei = j;
if (si != -1 and ei != -1) {
while (si <= ei) {
if (s[si] == '0' or s[ei] == '0' )
return false ;
si++;
ei--;
}
return true ;
}
i++;
j--;
}
return true ;
}
int main()
{
string s = "00011111111100000" ;
checkString(s) ? cout << "VALID\n"
: cout << "NOT VALID\n" ;
return 0;
}
|
Python3
def check_string(s):
i, j = 0 , len (s) - 1
si, ei = - 1 , - 1
while i < = j:
if si = = - 1 and s[i] = = '1' :
si = i
if ei = = - 1 and s[j] = = '1' :
ei = j
if si ! = - 1 and ei ! = - 1 :
while si < = ei:
if s[si] = = '0' or s[ei] = = '0' :
return False
si + = 1
ei - = 1
return True
i + = 1
j - = 1
return True
s = "00011111111100000"
print ( "VALID" if check_string(s) else "NOT VALID" )
|
Java
import java.util.Scanner;
public class Main {
public static boolean checkString(String s)
{
int i = 0 , j = s.length() - 1 ;
int si = - 1 , ei = - 1 ;
while (i <= j) {
if (si == - 1 && s.charAt(i) == '1' )
si = i;
if (ei == - 1 && s.charAt(j) == '1' )
ei = j;
if (si != - 1 && ei != - 1 ) {
while (si <= ei) {
if (s.charAt(si) == '0'
|| s.charAt(ei) == '0' )
return false ;
si++;
ei--;
}
return true ;
}
i++;
j--;
}
return true ;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String s = "00011111111100000" ;
if (checkString(s)) {
System.out.println( "VALID" );
}
else {
System.out.println( "NOT VALID" );
}
}
}
|
C#
using System;
class Program {
static bool CheckString( string s)
{
int i = 0, j = s.Length - 1;
int si = -1, ei = -1;
while (i <= j) {
if (si == -1 && s[i] == '1' )
si = i;
if (ei == -1 && s[j] == '1' )
ei = j;
if (si != -1 && ei != -1) {
while (si <= ei) {
if (s[si] == '0' || s[ei] == '0' )
return false ;
si++;
ei--;
}
return true ;
}
i++;
j--;
}
return true ;
}
static void Main( string [] args)
{
string s = "00011111111100000" ;
if (CheckString(s))
Console.WriteLine( "VALID" );
else
Console.WriteLine( "NOT VALID" );
}
}
|
Javascript
function check_string(s) {
let i = 0, j = s.length - 1;
let si = -1, ei = -1;
while (i <= j) {
if (si == -1 && s[i] == '1' ) {
si = i;
}
if (ei == -1 && s[j] == '1' ) {
ei = j;
}
if (si != -1 && ei != -1) {
while (si <= ei) {
if (s[si] == '0' || s[ei] == '0' ) {
return false ;
}
si += 1;
ei -= 1;
}
return true ;
}
i += 1;
j -= 1;
}
return true ;
}
let s = "00011111111100000" ;
console.log(check_string(s) ? "VALID" : "NOT VALID" );
|
Time Complexity : O(N)
Auxiliary Space : O(1), since it is using constant space for variables.
Similar Reads
Check if a binary string has a 0 between 1s or not | Set 2 (Regular Expression Approach)
Given a string of 0 and 1, we need to check that the given string is valid or not. The given string is valid when there is no zero is present in between 1's. For example, 1111, 0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not. Examples: Input : 100 Output : VALID Input : 111000
3 min read
Check if all substrings of length K of a Binary String has equal count of 0s and 1s
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
6 min read
Find all the patterns of "1(0+)1" in a given string (General Approach)
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0's. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern.
5 min read
Check if a binary string contains consecutive same or not
Given a binary string str consisting of characters '0' and '1'. The task is to find whether the string is valid or not. A string is valid only if the characters are alternating i.e. no two consecutive characters are the same. Examples: Input: str[] = "010101" Output: Valid Input: str[] = "010010" Ou
4 min read
Converting a Real Number (between 0 and 1) to Binary String
Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print" ERROR:' Examples: Input : (0.625)10 Output : (0.101)2 Input : (0.72)10 Output : ERROR Solution:
12 min read
Check if any circular rotation of String has at most X 1s between two adjacent 0s
Given a binary string S of length N and an integer X, the task is to check if there exists a right wise circular rotation of the string such that every 2 adjacent 0?s are separated by at most X 1?s. Note: The first and the last 0s in the string are not considered to be adjacent Examples: Input: S =
11 min read
Check if count of 1s can be made greater in a Binary string by changing 0s adjacent to 1s
Given a binary string S of size N, the task is to check if the count of 1s can be made greater than the count of 0s by changing the 0s adjacent to 1s to any other characters. If it is possible, then print Yes. Otherwise, print No. Note: Any index having 1 can be chosen at most once. Examples: Input:
9 min read
Check if a number has bits in alternate pattern | Set-2 O(1) Approach
Given a positive integer n. The problem is to check whether this integer has an alternate pattern in its binary representation or not. Here alternate pattern means that the set and unset bits in n occur in alternate order. For example- 5 has an alternate pattern i.e. 101. Print âYesâ if it has an al
6 min read
Segregate 1s and 0s in separate halves of a Binary String
Given a binary string str of even length, consisting of equal number of 0s and 1s, the task is to segregate all 1s and 0s into separate halves by repeatedly reversing a substring. Print the minimum count of reversals required. Examples: Input: str = "01011100"Output: 2Explanation: The operations per
5 min read
Check if K '0's can be flipped such that Binary String contains no pair of adjacent '1's
Given a binary string S of length N and an integer K, the task is to check if it is possible to flip K 0s such that the resulting string does not contain any pair of adjacent 1s. If it is possible to do so, then print "Yes". Otherwise, print "No". Input: S = "01001001000", K = 1Output: YesExplanatio
9 min read