Open In App

Check if a binary string has a 0 between 1s or not | Set 1 (General approach)

Improve
Improve
Like Article
Like
Save
Share
Report

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
Recommended Practice

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++




// C++ program to check if a string is valid or not.
#include <bits/stdc++.h>
using namespace std;
 
// Function returns 1 when string is valid
// else returns 0
bool checkString(string s)
{
    int len = s.length();
 
    // Find first occurrence of 1 in s[]
    int first = s.size() + 1;
    for (int i = 0; i < len; i++) {
        if (s[i] == '1') {
            first = i;
            break;
        }
    }
 
    // Find last occurrence of 1 in s[]
    int last = 0;
    for (int i = len - 1; i >= 0; i--) {
        if (s[i] == '1') {
            last = i;
            break;
        }
    }
 
    // Check if there is any 0 in range
    for (int i = first; i <= last; i++)
        if (s[i] == '0')
            return false;
 
    return true;
}
 
// Driver code
int main()
{
    string s = "00011111111100000";
    checkString(s) ? cout << "VALID\n" : cout << "NOT VALID\n";
    return 0;
}


Java




// Java program to check if a string is valid or not.
 
class Test {
    // Method returns 1 when string is valid
    // else returns 0
    static boolean checkString(String s)
    {
        int len = s.length();
 
        // Find first occurrence of 1 in s[]
        int first = 0;
        for (int i = 0; i < len; i++) {
            if (s.charAt(i) == '1') {
                first = i;
                break;
            }
        }
 
        // Find last occurrence of 1 in s[]
        int last = 0;
        for (int i = len - 1; i >= 0; i--) {
            if (s.charAt(i) == '1') {
                last = i;
                break;
            }
        }
 
        // Check if there is any 0 in range
        for (int i = first; i <= last; i++)
            if (s.charAt(i) == '0')
                return false;
 
        return true;
    }
 
    // Driver method
    public static void main(String args[])
    {
        String s = "00011111111100000";
        System.out.println(checkString(s) ? "VALID" : "NOT VALID");
    }
}


Python




# Python3 program to check if
# a string is valid or not.
 
# Function returns 1 when
# string is valid else
# returns 0
def checkString(s):
   
    Len = len(s)
     
    # Find first occurrence
    # of 1 in s[]
    first = len(s) + 1
 
    for i in range(Len):
        if(s[i] == '1'):
            first = i
            break
 
    # Find last occurrence
    # of 1 in s[]
    last = 0
 
    for i in range(Len - 1,
                   -1, -1):
        if(s[i] == '1'):
            last = i
            break
 
    # Check if there is any
    # 0 in range
    for i in range(first,
                   last + 1):
        if(s[i] == '0'):
            return False
    return True
 
# Driver code
s = "00011111111100000"
if(checkString(s)):
    print("VALID")
else:
    print("NOT VALID")
 
# This code is contributed by avanitrachhadiya2155


C#




// C# program to check if a
// string is valid or not.
using System;
 
class GFG {
     
    // Method returns 1 when string is valid
    // else returns 0
    static bool checkString(String s)
    {
        int len = s.Length;
 
        // Find first occurrence of 1 in s[]
        int first = 0;
        for (int i = 0; i < len; i++) {
            if (s[i] == '1') {
                first = i;
                break;
            }
        }
 
        // Find last occurrence of 1 in s[]
        int last = 0;
        for (int i = len - 1; i >= 0; i--) {
            if (s[i] == '1') {
                last = i;
                break;
            }
        }
 
        // Check if there is any 0 in range
        for (int i = first; i <= last; i++)
            if (s[i] == '0')
                return false;
 
        return true;
    }
 
    // Driver method
    public static void Main()
    {
        string s = "00011111111100000";
        Console.WriteLine(checkString(s) ?
                   "VALID" : "NOT VALID");
    }
}
 
// This code is contributed by Sam007


Javascript




<script>
 
    // JavaScript program to check 
    // if a string is valid or not.
     
    // Method returns 1 when string is valid
    // else returns 0
    function checkString(s)
    {
        let len = s.length;
   
        // Find first occurrence of 1 in s[]
        let first = 0;
        for (let i = 0; i < len; i++) {
            if (s[i] == '1') {
                first = i;
                break;
            }
        }
   
        // Find last occurrence of 1 in s[]
        let last = 0;
        for (let i = len - 1; i >= 0; i--) {
            if (s[i] == '1') {
                last = i;
                break;
            }
        }
   
        // Check if there is any 0 in range
        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>


Output

VALID

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++




// C++ program to check if a string is valid or not.
#include <bits/stdc++.h>
using namespace std;
 
// Function returns 1 when string is valid
// else returns 0
bool checkString(string s)
{
    // two pointers i and j will point
    // to both end of the string
    int i = 0, j = s.size() - 1;
 
    // si and ei the other two variables
    int si = -1, ei = -1;
 
    while (i <= j) {
        // if 1 is found in the left part
        // for the first time
        if (si == -1 and s[i] == '1')
            si = i;
 
        // if 1 is found in the right part
        // for the first time
        if (ei == -1 and s[j] == '1')
            ei = j;
 
        // if 1 is found in both side
        if (si != -1 and ei != -1) {
            // use the other two pointers
            // to check if there is zero
            while (si <= ei) {
                // if in any side 0 is found
                // return false
                if (s[si] == '0' or s[ei] == '0')
                    return false;
 
                si++;
                ei--;
            }
 
            // if not found
            // return true
            return true;
        }
 
        // update the initial pointers
        i++;
        j--;
    }
 
    // if it is not invalid
    // return true
    return true;
}
 
// Driver code
int main()
{
    string s = "00011111111100000";
    checkString(s) ? cout << "VALID\n"
                   : cout << "NOT VALID\n";
    return 0;
}
 
// This code is contributed by Rajdeep Mallick(rajdeep999)


Python3




# Python program to check if a string is valid or not.
 
 
# Function returns 1 when string is valid
# else returns 0
def check_string(s):
   
    # two pointers i and j will point
    # to both end of the string
    i, j = 0, len(s) - 1
     
    # si and ei the other two variables
    si, ei = -1, -1
     
    while i <= j:
        # if 1 is found in the left part
        # for the first time
        if si == -1 and s[i] == '1':
            si = i
             
        # if 1 is found in the right part
        # for the first time
        if ei == -1 and s[j] == '1':
            ei = j
             
        # if 1 is found in both side
        if si != -1 and ei != -1:
           
            # use the other two pointers
            # to check if there is zero
            while si <= ei:
               
                # if in any side 0 is found
                # return false
                if s[si] == '0' or s[ei] == '0':
                    return False
                si += 1
                ei -= 1
                 
            # if not found
            # return true
            return True
        # update the initial pointers
        i += 1
        j -= 1
         
    # if it is not invalid
    # return true
    return True
 
# Driver code
s = "00011111111100000"
print("VALID" if check_string(s) else "NOT VALID")
 
# This code is contributed by Akash Bankar(thebeginner01)


Java




// Java program to check if a string is valid or not.
import java.util.Scanner;
 
public class Main {
   
    // Function returns 1 when string is valid
    // else returns 0
    public static boolean checkString(String s)
    {
       // two pointers i and j will point
       // to both end of the string
        int i = 0, j = s.length() - 1;
       
        // si and ei the other two variables
        int si = -1, ei = -1;
 
        while (i <= j) {
           
            // if 1 is found in the left part
            // for the first time
            if (si == -1 && s.charAt(i) == '1')
                si = i;
 
            // if 1 is found in the right part
            // for the first time
            if (ei == -1 && s.charAt(j) == '1')
                ei = j;
            // if 1 is found in both side
            if (si != -1 && ei != -1) {
               
                // use the other two pointers
                // to check if there is zero
                while (si <= ei) {
                   
                    // if in any side 0 is found
                    // return false
                    if (s.charAt(si) == '0'
                        || s.charAt(ei) == '0')
                        return false;
 
                    si++;
                    ei--;
                }
               
                // if not found
                // return true
                return true;
            }
      // update the initial pointers
            i++;
            j--;
        }
       
        // if it is not invalid
        // return true
        return true;
    }
   
// Driver code
    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");
        }
    }
}
// This code is contributed by Akash Bankar(thebeginner01)


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




// The function returns true if the string is valid
// and false if it is invalid.
function check_string(s) {
 
// two pointers i and j will point
// to both end of the string
let i = 0, j = s.length - 1;
 
// si and ei the other two variables
let si = -1, ei = -1;
 
while (i <= j) {
// if 1 is found in the left part
// for the first time
if (si == -1 && s[i] == '1') {
si = i;
}// if 1 is found in the right part
// for the first time
if (ei == -1 && s[j] == '1') {
  ei = j;
}
 
// if 1 is found in both sides
if (si != -1 && ei != -1) {
   
  // use the other two pointers
  // to check if there is zero
  while (si <= ei) {
    // if in any side 0 is found
    // return false
    if (s[si] == '0' || s[ei] == '0') {
      return false;
    }
    si += 1;
    ei -= 1;
  }
  // if not found
  // return true
  return true;
}
 
// update the initial pointers
i += 1;
j -= 1;
}
 
// if it is not invalid
// return true
return true;
}
 
// Driver code
let s = "00011111111100000";
console.log(check_string(s) ? "VALID" : "NOT VALID");


Output

VALID

Time Complexity : O(N)
Auxiliary Space : O(1), since it is using constant space for variables.

 



Last Updated : 18 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads