Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Techniques to Find Consecutive 1s or 0s in a Python String
Next article icon

Techniques to Find Consecutive 1s or 0s in a Python String

Last Updated : 23 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a binary string and a number m, and we have to check if the string has m consecutive 1’s or 0’s. Below are a few examples to understand the problem statement clearly.

Examples:

Input: str = “001001”, m = 2 
Output: True
Explanation: the string have 2 consecutive 0s

Input: str = “1000000001”, m = 10
Output: False
Explanation: the string neither has 10 consecutive 0s or 1s

Check If a Binary String has m Consecutive

Now let us see a few different approaches to check if a binary string has m consecutive 1s or 0s in Python.

Brute Force Approach

In this method, we will check each character in the string one by one. Two counter variables are taken to track the count of 0s and 1s. Then iterating through each character using for loop, the counter variables are updated. For each character, the value of its counter is increased by one while the other's is reset to 0. Then check if any counter has reached the value m, return True.

Example: In this example, the counter variables are initialized to 0 and then using for loop each character is extracted from the string and its corresponding counter is increased while the other is reset. Then each counter is checked if it matched the value of m or not.

Python
def has_consecutive(s, m):     # Initialize counters for consecutive 1s and 0s     count_1 = count_0 = 0          #  Loop through each character in the string     for char in s:         #  Update counters          if char == '1':             count_1 += 1             count_0 = 0         elif char == '0':             count_0 += 1             count_1 = 0                  # Check if any counter has reached m         if count_1 >= m or count_0 >= m:             return True          return False  s = "11110000111111" m = 4 print(has_consecutive(s, m))   

Output:

True

Using String Methods

In this method, we are using the Python string property where when a string is multiplied with an integer, it returns the integer-times string. That is, we we write 5*'a', it will give us 'aaaaa'. Using this technique, we will define two target strings, for 0 and 1. Then we will check for the target string in the given string. If the target string is found in the given string, return True.

Example: In this example, two target strings are initialized by multiplying 0 and 1 with the m. Then these target string are checked for in the given string using Python membership operator - in.

Python
def has_consecutive(s, m):     # Create target strings with m consecutive '1's and '0's     target_1 = '1' * m     target_0 = '0' * m          # Check if either target string is a substring of s     return target_1 in s or target_0 in s  s = "11110001" m = 4 print(has_consecutive(s, m))   

Output:

True

Using Regular Expression

This method is quite similar to the previous one. In this method we are using Python Regular Expression module to check for a specific pattern. The search() function of this module is used to search for a specific patter. It takes two arguments, the first is the pattern to be searched, and second is the string in which the pattern is to be searched.

Example: In this example, we first import the regular expression module. Then define the target pattern using string multiplication technique. Then the search() function checks if the target string is in the original string or not.

Python
import re  def has_consecutive(s, m):     # Create target strings with m consecutive '1's and '0's     target_1 = '1' * m     target_0 = '0' * m          # Check if either target string is a substring of s     if re.search(target_1, s) or re.search(target_0, s):         return True              return False  s = "1001010" m = 3 print(has_consecutive(s, m))   

Output:

False

Next Article
Techniques to Find Consecutive 1s or 0s in a Python String

B

bug8wdqo
Improve
Article Tags :
  • Python
  • Python Programs
  • python-basics
Practice Tags :
  • python

Similar Reads

    Python - First K consecutive digits in String
    Given a String and number K, extract first K consecutive digits making number. Input : test_str = "geeks5geeks43best", K = 2 Output : 43 Explanation : 43 is first 2 consecutive digits. Input : test_str = "geeks5gee2ks439best", K = 3 Output : 439 Explanation : 439 is first 3 consecutive digits. Metho
    5 min read
    Find the Index of a Substring in Python
    Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python.Using str.find() The find() method searches for the first occurrence of the specified substring and return
    3 min read
    Find Longest Consecutive Letter and Digit Substring - Python
    The task is to identify the longest sequence of consecutive letters or digits in a given string. A consecutive letter or digit refers to a substring where each character is adjacent to the next one in the alphabet for letters or numerically for digits. It involves identifying the longest sequence of
    4 min read
    Check if all the 1s in a binary string are equidistant or not in Python
    We are given a binary string, we have to check if the distance between every two 1s is the same or not. Below are a few examples to understand the problem clearly. Example: Input: “00111000” Output: TrueExplanation: The distance between all the 1’s is same and is equal to 1.Input: “0101001” Output:
    3 min read
    How to Get Index of a Substring in Python?
    To get index of a substring within a Python string can be done using several methods such as str.find(), str.index(), and even regular expressions. Each approach has its own use case depending on the requirements. Let’s explore how to efficiently get the index of a substring.The simplest way to get
    2 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