Open In App

Check if given Binary string follows then given condition or not

Last Updated : 12 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given binary string str, the task is to check whether the given string follows the below condition or not: 
 

  • String starts with a '1'.
  • Each '1' is followed by empty string(""), '1', or "00".
  • Each "00" is followed by empty string(""), '1'.


If the given string follows the above criteria then print "Valid String" else print "Invalid String".
Examples: 
 

Input: str = "1000" 
Output: False 
Explanation: 
The given string starts with "1" and has "00" followed by the "1" which is not the given criteria. 
Hence, the given string is "Invalid String".
Input: str = "1111" 
Output: True 
Explanation: 
The given string starts with 1 and has 1 followed by all the 1's. 
Hence, the given string is "Valid String". 
 

Approach:

  1. Check if the first character of the string is '1', if not, return false.
  2. Traverse the string character by character, starting from the second character.
  3. If the current character is '1', move to the next character.
  4. If the current characters are "00", move two characters ahead and check if the next character is '1', if not, return false.
  5. If the current character is neither '1' nor "00", return false.
  6. If we reach the end of the string without returning false, the string is valid. Return true.

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Output
Valid String

Time Complexity: O(N)

Auxiliary Space: O(1)


Approach: The idea is to use Recursion. Below are the steps: 
 

  1. Check whether 0th character is '1' or not. If it is not '1', return false as the string is not following condition 1.
  2. To check the string satisfying the second condition, recursively call for a string starting from 1st index using substr() function in C++.
  3. To check the string satisfying the third condition, first, we need to check if the string length is greater than 2 or not. If yes, then check if '0' is present at the first and second index. If yes, then recursively call for the string starting from 3rd index.
  4. At any recursive call, If the string is empty, then we have traversed the complete string satisfying all the given conditions and print "Valid String".
  5. At any recursive call, If the given condition doesn't satisfy then stop that recursion and print "Invalid String".


Below is the implementation of the above approach:
 

C++
Java Python3 C# JavaScript

Output
Valid String

Time Complexity: O(N), where N is the length of string. 
Auxiliary Space: O(1).


Article Tags :

Similar Reads