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
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
Find all the patterns of "1(0+)1" in a given string (General Approach)
Next article icon

Count of occurrences of a "1(0+)1" pattern in a string

Last Updated : 15 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an alphanumeric string, find the number of times a pattern 1(0+)1 occurs in the given string. Here, (0+) signifies the presence of non empty sequence of consecutive 0's.

Examples: 

Input : 1001010001 Output : 3 First sequence is in between 0th and 3rd index. Second sequence is in between 3rd and 5th index. Third sequence is in between 5th and 9th index. So total number of sequences comes out to be 3.  Input : 1001ab010abc01001 Output : 2 First sequence is in between 0th and 3rd index. Second valid sequence is in between 13th and 16th index. So total number of sequences comes out to  be 2.

The idea to solve this problem is to first find a '1' and keep moving forward in the string and check as mentioned below: 

  1. If any character other than '0' and '1' is obtained then it means pattern is not valid. So we go on in the search of next '1' from this index and repeat these steps again. 
  2. If a '1' is seen, then check for the presence of '0' at previous position to check the validity of sequence.

Below is the implementation of above idea: 

C++
// C++ program to calculate number of times // the pattern occurred in given string #include<iostream> using namespace std;  // Returns count of occurrences of "1(0+)1" // int str. int countPattern(string str) {     int len = str.size();     bool oneSeen = 0;      int count = 0;  // Initialize result     for (int i = 0; i < len ; i++)     {          // Check if encountered '1' forms a valid         // pattern as specified         if (str[i] == '1' && oneSeen == 1)             if (str[i - 1] == '0')                 count++;          // if 1 encountered for first time         // set oneSeen to 1         if (str[i] == '1' && oneSeen == 0)            {             oneSeen = 1;             continue;            }         // Check if there is any other character         // other than '0' or '1'. If so then set         // oneSeen to 0 to search again for new         // pattern         if (str[i] != '0' && str[i] != '1')             oneSeen = 0;       }      return count; }  // Driver program to test above function int main() {     string str = "100001abc101";     cout << countPattern(str);     return 0; } 
Java
//Java program to calculate number of times //the pattern occurred in given string public class GFG {     // Returns count of occurrences of "1(0+)1"     // int str.     static int countPattern(String str)     {         int len = str.length();         boolean oneSeen = false;                  int count = 0;  // Initialize result         for(int i = 0; i < len ; i++)         {             char getChar = str.charAt(i);                          // Check if encountered '1' forms a valid             // pattern as specified             if (getChar == '1' && oneSeen == true){                 if (str.charAt(i - 1) == '0')                     count++;             }              // if 1 encountered for first time             // set oneSeen to 1             if(getChar == '1' && oneSeen == false)                 oneSeen = true;                          // Check if there is any other character             // other than '0' or '1'. If so then set             // oneSeen to 0 to search again for new             // pattern             if(getChar != '0' && str.charAt(i) != '1')                 oneSeen = false;                       }         return count;     }      // Driver program to test above function     public static void main(String[] args)     {          String str = "100001abc101";          System.out.println(countPattern(str));     }  } // This code is contributed by Sumit Ghosh 
Python3
# Python program to calculate number of times # the pattern occurred in given string  # Returns count of occurrences of "1(0+)1" def countPattern(s):     length = len(s)     oneSeen = False          count = 0   # Initialize result     for i in range(length):          # Check if encountered '1' forms a valid         # pattern as specified         if (s[i] == '1' and oneSeen):             if (s[i - 1] == '0'):                 count += 1          # if 1 encountered for first time         # set oneSeen to 1         if (s[i] == '1' and oneSeen == 0):             oneSeen = True           # Check if there is any other character         # other than '0' or '1'. If so then set         # oneSeen to 0 to search again for new         # pattern         if (s[i] != '0' and s[i] != '1'):             oneSeen = False          return count  # Driver code s = "100001abc101" print(countPattern(s))  # This code is contributed by Sachin Bisht 
C#
// C# program to calculate number // of times the pattern occurred  // in given string  using System;  class GFG { // Returns count of occurrences  // of "1(0+)1" int str.  public static int countPattern(string str) {     int len = str.Length;     bool oneSeen = false;      int count = 0; // Initialize result     for (int i = 0; i < len ; i++)     {         char getChar = str[i];          // Check if encountered '1' forms          // a valid pattern as specified          if (getChar == '1' &&                   oneSeen == true)         {             if (str[i - 1] == '0')             {                 count++;             }         }          // if 1 encountered for first         // time set oneSeen to 1          if (getChar == '1' &&              oneSeen == false)         {             oneSeen = true;         }          // Check if there is any other character          // other than '0' or '1'. If so then set          // oneSeen to 0 to search again for new          // pattern          if (getChar != '0' &&                   str[i] != '1')         {             oneSeen = false;         }       }     return count; }  // Driver Code public static void Main(string[] args) {     string str = "100001abc101";     Console.WriteLine(countPattern(str)); }  }  // This code is contributed  // by Shrikant13 
PHP
<?php  // PHP program to calculate number of times // the pattern occurred in given string  // Returns count of occurrences  // of "1(0+)1"  function countPattern($str) {     $len = strlen($str);     $oneSeen = 0;      $count = 0; // Initialize result     for ($i = 0; $i < $len ; $i++)     {         // Check if encountered '1' forms a         // valid pattern as specified         if ($str[$i] == '1' && $oneSeen == 1)             if ($str[$i - 1] == '0')                 $count++;          // if 1 encountered for first          // time set oneSeen to 1         if ($str[$i] == '1' && $oneSeen == 0)             $oneSeen = 1;          // Check if there is any other character         // other than '0' or '1'. If so then set         // oneSeen to 0 to search again for new         // pattern         if ($str[$i] != '0' && $str[$i] != '1')             $oneSeen = 0;       }      return $count; }  // Driver Code $str = "100001abc101"; echo countPattern($str);  // This code is contributed  // by ChitraNayal ?> 
JavaScript
<script> //Javascript program to calculate number of times //the pattern occurred in given string          // Returns count of occurrences of "1(0+)1"     // int str.     function countPattern(str)     {         let len = str.length;         let oneSeen = false;                    let count = 0;  // Initialize result         for(let i = 0; i < len ; i++)         {             let getChar = str[i];                            // Check if encountered '1' forms a valid             // pattern as specified             if (getChar == '1' && oneSeen == true){                 if (str[i-1] == '0')                     count++;             }                // if 1 encountered for first time             // set oneSeen to 1             if(getChar == '1' && oneSeen == false)                 oneSeen = true;                            // Check if there is any other character             // other than '0' or '1'. If so then set             // oneSeen to 0 to search again for new             // pattern             if(getChar != '0' && str[i] != '1')                 oneSeen = false;                           }         return count;     }          // Driver program to test above function     let str = "100001abc101";     document.write(countPattern(str));          //This code is contributed by avanitrachhadiya2155      </script> 

Output
2

Time Complexity: O( N ), where N is the length of input string.
Auxiliary Space: O(1), as extra space is not required

If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected].  


Next Article
Find all the patterns of "1(0+)1" in a given string (General Approach)

S

Sakshi Tiwari
Improve
Article Tags :
  • Misc
  • Strings
  • Pattern Searching
  • DSA
  • binary-string
Practice Tags :
  • Misc
  • Pattern Searching
  • Strings

Similar Reads

  • Count occurrences of a character in a repeated string
    Given an integer N and a lowercase string. The string is repeated infinitely. The task is to find the No. of occurrences of a given character x in first N letters.Examples: Input : N = 10 str = "abcac"Output : 4Explanation: "abcacabcac" is the substring from the infinitely repeated string. In first
    8 min read
  • Count occurrences of a word in string
    Given a two strings s and word. The task is to count the number of occurrences of the string word in the string s.Note: The string word should appear in s as a separate word, not as a substring within other words. Examples: Input: s = "GeeksforGeeks A computer science portal for geeks", word = "port
    11 min read
  • Count Occurrences of a Given Character in a String
    Given a string S and a character 'c', the task is to count the occurrence of the given character in the string. Examples: Input : S = "geeksforgeeks" and c = 'e'Output : 4Explanation: 'e' appears four times in str. Input : S = "abccdefgaa" and c = 'a' Output : 3Explanation: 'a' appears three times i
    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
  • Count the number of occurrences of a particular digit in a number
    Given a number N and a digit D, the task is to count the occurrences of D in N.Examples: Input: N = 25, D = 2 Output: 1 Input: N = 100, D = 0 Output: 2 Naive Approach: The basic idea is to loop through the digits of the number and keep a count of the occurrences of each digit in a hash table. Then,
    7 min read
  • Count of occurrences of each prefix in a string using modified KMP algorithm
    Given a string S of size N, the task is to count the occurrences of all the prefixes of the given string S. Examples: Input: S = "AAAA" Output: A occurs 4 times AA occurs 3 times. AAA occurs 2 times. AAAA occurs 1 times. Explanation: Below is the illustration of all the prefix: Input: S = "ABACABA"
    15 min read
  • Count occurrences of a word in string | Set 2 (Using Regular Expressions)
    Given a string str and a word w, the task is to print the number of the occurrence of the given word in the string str using Regular Expression. Examples: Input: str = "peter parker picked a peck of pickled peppers”, w = "peck"Output: 1Explanation: There is only one occurrence of the word "peck" in
    4 min read
  • Count occurrences of strings formed using words in another string
    Given a string A and a vector of strings B, the task is to count the number of strings in vector B that only contains the words from A. Examples: Input: A="blue green red yellow"B[]={"blue red", "green pink", "yellow green"}Output: 2 Input: A="apple banana pear"B[]={"apple", "banana apple", "pear ba
    7 min read
  • Count of substrings of a Binary string containing only 1s
    Given a binary string of length N, we need to find out how many substrings of this string contain only 1s. Examples: Input: S = "0110111"Output: 9Explanation:There are 9 substring with only 1's characters. "1" comes 5 times. "11" comes 3 times. "111" comes 1 time. Input: S = "000"Output: 0 The_Appro
    6 min read
  • Count Substrings with number of 0s and 1s in ratio of X : Y
    Given a binary string S, the task is to count the substrings having the number of 0s and 1s in the ratio of X : Y Examples: Input: S = "010011010100", X = 3, Y = 2Output: 5Explanation: The index range for the 5 substrings are: (0, 4), (2, 6), (6, 10), (7, 11), (2, 11) Input: S = "10010101", X = 1, Y
    7 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