Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Count of possible distinct Binary strings after replacing "11" with "0"
Next article icon

Check if substring “10” occurs in the given binary string in all possible replacements of ‘?’ with 1 or 0

Last Updated : 26 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S consisting of only ‘0’, ‘1’ and ‘?’, the task is to check if there exists a substring “10” in every possible replacement of the character ‘?’ with either 1 or 0.

Examples:

Input: S = “1?0”
Output: Yes
Explanation:
Following are all the possible replacements of ‘?’:

  1. Replacing the ‘?’ with 0 modifies the string to “100”. In the modifies string, the substring “10” occurs.
  2. Replacing the ‘?’ with 1 modifies the string to “110”. In the modifies string, the substring “10” occurs.

From the above all possible replacements, the substring “10” occurs in all the replacements, therefore, print Yes.

Input: S= “??”
Output: No

Approach: The given problem can be solved by using a Greedy Approach which is based on the observation that if the string S contains many consecutive ‘?’, it can be replaced with a single ‘?’ as in the worst case we can replace it with all 1s or 0s.

Therefore, the idea is to create a new string from the given string S by replacing continuous ‘?’ with single ‘?’ and then check if there exists “10” or “1?0” as a substring, then it is possible to get “10” as substring after all possible replacements, therefore, print Yes. Otherwise, print No.

Below is the implementation of the above approach: 

C++




// C++ Program to implement
// the above approach
#include <iostream>
using namespace std;
 
// Function to check it possible to get
// "10" as substring after all possible
// replacements
string check(string S, int n)
{
 
  // Initialize empty string ans
  string ans = "";
  int c = 0;
 
  // Run loop n times
  for (int i = 0; i < n; i++) {
 
    // If char is "?", then increment
    // c by 1
    if (S[i] == '?') {
      c++;
    }
    else {
 
      // Continuous '?' characters
      if (c) {
        ans += "?";
      }
      c = 0;
      ans += S[i];
    }
  }
 
  // Their is no consecutive "?"
  if (c) {
    ans += "?";
  }
 
  // Check if "10" or "1?0" exists
  // in the string ans or not
  if (ans.find("10") != -1 || ans.find("1?0") != -1) {
    return "Yes";
  }
  else {
    return "No";
  }
}
 
// Driver code
int main()
{
  string S = "1?0";
  int n = S.size();
  string ans = check(S, n);
  cout << ans;
  return 0;
}
// This code is contributed by parthmanchanda81
 
 

Java




// Java program for the above approach
import java.io.*;
 
class GFG {
 
 
 // Returns true if s1 is substring of s2
    static int isSubstring(String s1, String s2)
    {
        int M = s1.length();
        int N = s2.length();
   
        /* A loop to slide pat[] one by one */
        for (int i = 0; i <= N - M; i++) {
            int j;
   
            /* For current index i, check for
            pattern match */
            for (j = 0; j < M; j++)
                if (s2.charAt(i + j) != s1.charAt(j))
                    break;
   
            if (j == M)
                return i;
        }
   
        return -1;
    }
   
  
// Function to check it possible to get
// "10" as substring after all possible
// replacements
static String check(String S, int n)
{
  
  // Initialize empty string ans
  String ans = "";
  int c = 0;
  
  // Run loop n times
  for (int i = 0; i < n; i++) {
  
    // If char is "?", then increment
    // c by 1
    if (S.charAt(i) == '?') {
      c++;
    }
    else {
  
      // Continuous '?' characters
      if (c != 0) {
        ans += "?";
      }
      c = 0;
      ans += S.charAt(i);
    }
  }
  
  // Their is no consecutive "?"
  if (c != 0) {
    ans += "?";
  }
  
  // Check if "10" or "1?0" exists
  // in the string ans or not
  if (isSubstring("10", S) != -1 || isSubstring("1?0", S) != -1) {
    return "Yes";
  }
  else {
    return "No";
  }
}
 
// Driver Code
public static void main (String[] args)
{
    String S = "1?0";
        int n = S.length();
        String ans = check(S, n);
        System.out.println(ans);
}
}
 
// This code is contributed by avijitmondal1998.
 
 

Python3




# Python program for the above approach
 
# Function to check it possible to get
# "10" as substring after all possible
# replacements
def check(S, n):
 
    # Initialize empty string ans
    ans = ""
    c = 0
 
    # Run loop n times
    for _ in range(n):
 
        # If char is "?", then increment
        # c by 1
        if S[_] == "?":
            c += 1
        else:
 
            # Continuous '?' characters
            if c:
                ans += "?"
 
            # Their is no consecutive "?"
            c = 0
            ans += S[_]
             
    # "?" still left
    if c:
        ans += "?"
 
    # Check if "10" or "1?0" exists
    # in the string ans or not
    if "10" in ans or "1?0" in ans:
        return "Yes"
    else:
        return "No"
 
 
# Driver Code
if __name__ == '__main__':
 
    S = "1?0"
    ans = check(S, len(S))
    print(ans)
 
 

C#




// C# program for the approach
using System;
using System.Collections.Generic;
 
class GFG {
 
 // Returns true if s1 is substring of s2
    static int isSubstring(string s1, string s2)
    {
        int M = s1.Length;
        int N = s2.Length;
  
        /* A loop to slide pat[] one by one */
        for (int i = 0; i <= N - M; i++) {
            int j;
  
            /* For current index i, check for
            pattern match */
            for (j = 0; j < M; j++)
                if (s2[i + j] != s1[j])
                    break;
  
            if (j == M)
                return i;
        }
  
        return -1;
    }
  
 
// Function to check it possible to get
// "10" as substring after all possible
// replacements
static string check(string S, int n)
{
 
  // Initialize empty string ans
  string ans = "";
  int c = 0;
 
  // Run loop n times
  for (int i = 0; i < n; i++) {
 
    // If char is "?", then increment
    // c by 1
    if (S[i] == '?') {
      c++;
    }
    else {
 
      // Continuous '?' characters
      if (c != 0) {
        ans += "?";
      }
      c = 0;
      ans += S[i];
    }
  }
 
  // Their is no consecutive "?"
  if (c != 0) {
    ans += "?";
  }
 
  // Check if "10" or "1?0" exists
  // in the string ans or not
  if (isSubstring("10", S) != -1 || isSubstring("1?0", S) != -1) {
    return "Yes";
  }
  else {
    return "No";
  }
}
 
    // Driver Code
    public static void Main()
    {
        string S = "1?0";
        int n = S.Length;
        string ans = check(S, n);
        Console.Write(ans);
    }
}
 
// This code is contributed by sanjoy_62.
 
 

Javascript




  <script>
        // JavaScript Program to implement
        // the above approach
 
        // Function to check it possible to get
        // "10" as substring after all possible
        // replacements
        function check(S, n) {
 
            // Initialize empty string ans
            ans = ""
            c = 0
 
            // Run loop n times
            for (let i = 0; i < n; i++) {
 
                // If char is "?", then increment
                // c by 1
                if (S[i] == "?")
                    c += 1
                else
 
                    // Continuous '?' characters
                    if (c != 0)
                        ans += "?"
 
                // Their is no consecutive "?"
                c = 0
                ans += S[i]
 
                // "?" still left
                if (c != 0)
                    ans += "?"
            }
             
            // Check if "10" or "1?0" exists
            // in the string ans or not
 
            if (ans.includes('10') || ans.includes('1?0'))
                return "Yes"
            else
                return "No"
 
        }
         
        // Driver Code
        S = "1?0"
        ans = check(S, S.length)
        document.write(ans)
 
// This code is contributed by Potta Lokesh
    </script>
 
 
Output: 
Yes

 

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

Note: The same approach can be used for substrings “00”/”01″/”11″ as well with minor changes.



Next Article
Count of possible distinct Binary strings after replacing "11" with "0"

H

harshitkap00r
Improve
Article Tags :
  • DSA
  • Greedy
  • Strings
  • binary-string
Practice Tags :
  • Greedy
  • Strings

Similar Reads

  • Check if binary representations of 0 to N are present as substrings in given binary string
    Give binary string str and an integer N, the task is to check if the substrings of the string contain all binary representations of non-negative integers less than or equal to the given integer N. Examples: Input: str = “0110", N = 3 Output: True Explanation: Since substrings “0", “1", “10", and “11
    9 min read
  • Minimum splits in a binary string such that every substring is a power of 4 or 6.
    Given a string S composed of 0 and 1. Find the minimum splits such that the substring is a binary representation of the power of 4 or 6 with no leading zeros. Print -1 if no such partitioning is possible. Examples: Input: 100110110 Output: 3 The string can be split into a minimum of three substrings
    11 min read
  • Check if given number contains only “01” and “10” as substring in its binary representation
    Given a number N, the task is to check if the binary representation of the number N has only "01" and "10" as a substring or not. If found to be true, then print "Yes". Otherwise, print "No".Examples: Input: N = 5 Output: Yes Explanation: (5)10 is (101)2 which contains only "01" and "10" as substrin
    6 min read
  • Check if N sized String with given number of 00, 01, 10, 11 Substrings exists
    Given an integer N and four values a, b, c, d (where a ≥ 0, b ≥ 0, c ≥ 0, d ≥ 0), the task is to check if it is possible to create a binary string of length N such that: There are exactly a substrings of "00" There are exactly b substrings of "01"There are exactly c substrings of "10"There are exact
    11 min read
  • Count of possible distinct Binary strings after replacing "11" with "0"
    Given a binary string str of size N containing 0 and 1 only, the task is to count all possible distinct binary strings when a substring "11" can be replaced by "0". Examples: Input: str = "11011"Output: 4Explanation: All possible combinations are "11011", "0011", "1100", "000". Input: str = "1100111
    15 min read
  • Count of substrings with equal ratios of 0s and 1s till ith index in given Binary String
    Given a binary string S, the task is to print the maximum number of substrings with equal ratios of 0s and 1s till the ith index from the start. Examples: Input: S = "110001"Output: {1, 2, 1, 1, 1, 2}Explanation: The given string can be partitioned into the following equal substrings: Valid substrin
    9 min read
  • Find if it is possible to make a binary string which contains given number of "0", "1" , "01" and "10" as sub sequences
    Given four integers l, m, x, and y. The task is to check whether it is possible to make a binary string consisting of l 0's, m 1's, x "01" and y "10" as sub-sequences in it.Examples: Input: l = 3, m = 2, x = 4, y = 2 Output: Yes Possible string is "00110". It contains 3 0's, 2 1's, 4 "01" sub-sequen
    4 min read
  • Count of substrings that start and end with 1 in given Binary String
    Given a binary string, count the number of substrings that start and end with 1. Examples: Input: "00100101"Output: 3Explanation: three substrings are "1001", "100101" and "101" Input: "1001"Output: 1Explanation: one substring "1001" Recommended PracticeCount SubstringsTry It!Count of substrings tha
    12 min read
  • Check if it is possible to rearrange a binary string with alternate 0s and 1s
    Given a binary string of length, at least two. We need to check if it is possible to rearrange a binary string such that there are alternate 0s and 1s. If possible, then the output is YES, otherwise the output is NO. Examples: Input : 1011 Output : NO We can't rearrange the string such that it has a
    5 min read
  • Split the binary string into substrings with equal number of 0s and 1s
    Given a binary string str of length N, the task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.Example: Input
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences