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:
Python - Check if there are K consecutive 1's in a binary number
Next article icon

Python - Check if there are K consecutive 1's in a binary number

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task is to check if a binary number (a string of 0s and 1s) has k consecutive 1s in it. The goal is to figure out if this pattern exists in the easiest and fastest way possible.

Using for loop

This method works by going through the string once and keeping track of how many '1's appear in a row. If the count reaches k more, it means we found what we were looking for, and we can stop early. If we see a character that’s not '1', we simply reset the count to zero and continue.

Python
s = "10101001111" k = 4   # Initialize counter count = 0    for char in s:      # If '1' found     if char == '1':           count += 1                  # If k consecutive 1's found         if count >= k:               print(True)             break     else:               # Reset counter if '0' found         count = 0  else:     print(False) 

Output
True 

Explanation:

  • This loop starts, and as it encounters '1' at positions 1, 3, and 6, the count is incremented.
  • When the loop reaches the substring '1111' at positions 7, 8, 9, and 10, the count becomes 4.
  • At this point, count >= 4 is true, so True is printed and the loop exits.

Table of Content

  • Using sliding window
  • Using find ()

Using sliding window

This method involves moving a "window" of size k across the string s. For each position of the window, we check if the substring within the window contains k consecutive '1's. If a match is found, we terminate early; otherwise, we continue sliding the window until the end of the string.

Python
s = "11100000" k = 5    # Loop through the string, considering every substring of length k for i in range(len(s) - k + 1):        # Check if the current substring of length k is made of only '1's     if s[i:i+k] == '1' * k:         print(True)         break else:     print(False) 

Output
False 

Explanation:

  • for i in range(len(s) - k + 1): This iterates through the string, checking all substrings of length k (5). This loop checks 4 substrings: "11100", "11000", "10000", and "00000".
  • Substring Comparison: This loop compares each substring s[i:i+k] with "11111". If a match is found, it prints True and exits the loop.
  • Else Block: If no match is found, the else block executes and prints False.

Using find ()

find () quickly locate a substring of k consecutive '1's in the string. The find method searches the string and returns the starting index of the substring if it exists or -1 if it doesn’t. Based on this, we determine whether the condition is satisfied.

Python
s = "10101001111" k = 4 if s.find("1" * k) != -1:     print(True) else:     print(False) 

Output
True 

Explanation:

  • s.find("1" * k): This checks if a substring of k consecutive '1's (e.g., "1111" when k=4) exists in the string s.
  • if s.find("1" * k) != -1: If the find() method returns an index (i.e., the substring is found), it prints True otherwise False .

Next Article
Python - Check if there are K consecutive 1's in a binary number

S

Striver
Improve
Article Tags :
  • Misc
  • Python
  • binary-string
  • python-string
Practice Tags :
  • Misc
  • python

Similar Reads

    1 to n bit numbers with no consecutive 1s in binary representation
    Given a number n, our task is to find all 1 to n bit numbers with no consecutive 1s in their binary representation.Examples: Input: N = 4 Output: 1 2 4 5 8 9 10 These are numbers with 1 to 4 bits and no consecutive ones in binary representation. Input: n = 3 Output: 1 2 4 5 Approach: There will be 2
    5 min read
    Check if a given string is binary string or not - Python
    The task of checking whether a given string is a binary string in Python involves verifying that the string contains only the characters '0' and '1'. A binary string is one that is composed solely of these two digits and no other characters are allowed. For example, the string "101010" is a valid bi
    3 min read
    Fibbinary Numbers (No consecutive 1s in binary)
    Given N, check if the number is a Fibbinary number or not. Fibbinary numbers are integers whose binary representation includes no consecutive ones. Examples: Input : 10 Output : YES Explanation: 1010 is the binary representation of 10 which does not contains any consecutive 1's. Input : 11 Output :
    5 min read
    Maximum length of consecutive 1's in a binary string in Python using Map function
    We are given a binary string containing 1's and 0's. Find the maximum length of consecutive 1's in it. Examples: Input : str = '11000111101010111' Output : 4 We have an existing solution for this problem please refer to Maximum consecutive one’s (or zeros) in a binary array link. We can solve this p
    1 min read
    Count number of binary strings without consecutive 1's
    Given a positive integer n, the task is to count all possible distinct binary strings of length n such that there are no consecutive 1's.Examples: Input: n = 3Output: 5Explanation: 5 strings are ("000", "001", "010", "100", "101").Input: n = 2Output: 3Explanation: 3 strings are ("00", "01", "10").Ta
    15+ 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