Open In App

Python | Check if there are K consecutive 1’s in a binary number

Last Updated : 31 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given K and a binary number, check if there exists k consecutive 1’s in the binary number. Examples:

Input: binary number = 101010101111
            k = 4 
Output: yes
Explanation: at the last 4 index there exists 4 consecutive 1’s

Input: binary number = 11100000 k=5 
Output: no
Explanation: There is a maximum of 3 consecutive 1’s in the given binary.

Approach: Create a new string with k 1’s. Using if condition check if there is new in s. In python if new in s: checks if there is any existence if new in s, hence returns true if there is else it returns a false. Below is the Python implementation of the above approach: 

Python




# Python program to check if there
# is k consecutive 1's in a binary number
 
# function to check if there are k
# consecutive 1's
def check(s,k):
     
    # form a new string of k 1's
    new = "1"*k
     
    # if there is k 1's at any position
    if new in s:
        print "yes"
    else:
        print "no"
 
# driver code
s = "10101001111"
k = 4
check(s, k)


Output

yes

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

Approach : Using find() method

Python3




# Python program to check if there
# is k consecutive 1's in a binary number
 
s = "10101001111"
k = 4
 
res = "NO"
 
if(s.find("1"*k) != -1):
    res = "YES"
 
print(res)


Output

YES

Time complexity: O(n), where n is the length of s. 
Auxiliary space: O(1), as we are only using a constant amount of memory for the string s, the integer k, and the string res.

Another approach to solve this problem is to use a sliding window approach. In this approach, we can check for the presence of k consecutive 1’s by considering a window of size k and sliding it through the entire binary number.

Here is an example of how this approach can be implemented in Python:

Python3




def check_consecutive_ones(s, k):
    for i in range(len(s) - k + 1):
        if all(s[i + j] == "1" for j in range(k)):
            return True
    return False
 
s = "10101001111"
k = 4
 
if check_consecutive_ones(s, k):
    print("Yes")
else:
    print("No")


Output

Yes

This approach uses a for loop to iterate through each possible starting index of a sequence of k 1’s in the binary string and then checks if all the subsequent characters in the string at those indices are 1’s using the all() function. If any sequence of k 1’s is found, the function returns True, otherwise, it returns False.

The time complexity of the check_consecutive_ones() function is O(n*k), where n is the length of the input string. This is because the function involves iterating through all the characters in the string and checking if there is a consecutive subsequence of k ones.
The Auxiliary Space of the check_consecutive_ones() function is O(k), The all() function returns True if all the elements in an iterable are True, and False otherwise. 

Approach : Using replace() and len() methods

Python3




# Python program to check if there
# is k consecutive 1's in a binary number
 
s = "10101001111"
k = 4
a="1"*k
res = "NO"
b=s.replace(a,"")
if(len(b)!=len(s)):
    res = "YES"
print(res)


Output

YES

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

Approach : Using operator.contains() method

Check whether k consecutive 1’s are present in given binary string using operator.contains() method

Python3




# Python program to check if there
# is k consecutive 1's in a binary number
 
s = "10101001111"
k = 4
a="1"*k
res = "NO"
import operator
if operator.contains(s,a):
    res="YES"
print(res)


Output

YES

Time Complexity : O(N) where N is the length of s. 

Auxiliary Space : O(1) as we are only using a constant amount of memory for the string s, the integer k, and the string res

Approach: Using  a regular expression

  • Imports the re module
  • Sets the input binary string and the number of consecutive 1’s to check using tuple unpacking
  • Searches for a pattern of k consecutive 1’s in the binary string using a regular expression with the re.search() function
  • Sets the result to “YES” if the pattern is found, and “NO” if it is not, using a ternary operator
  • Prints the result to the console.

Python3




import re
 
# Input binary string and number of consecutive 1's to check
s = "10101001111"
k = 4
 
# Create regular expression pattern to match k consecutive 1's
pattern = '1{' + str(k) + '}'
 
# Initialize result to "NO"
res = "NO"
 
# Search for pattern in binary string
if re.search(pattern, s):
   # If pattern is found, set result to "YES"
   res = "YES"
 
# Output the result
print(res)


Output

YES

Time Complexity: O(N) where N is the length of s.

Auxiliary Space: O(N) because the regular expression pattern is created based on the input value of k,.



Similar Reads

Count possible binary strings of length N without P consecutive 0s and Q consecutive 1s
Given three integers N, P, and Q, the task is to count all possible distinct binary strings of length N such that each binary string does not contain P times consecutive 0’s and Q times consecutive 1's. Examples: Input: N = 5, P = 2, Q = 3Output: 7Explanation: Binary strings that satisfy the given conditions are { “01010”, “01011”, “01101”, “10101”
15+ min read
Count of Binary strings having at most X consecutive 1s and Y consecutive 0s
Given two integers N and M (1 ≤ N, M ≤ 100) denoting the total number of 1s and 0s respectively. The task is to count the number of possible arrangements of these 0s and 1s such that any arrangement has at most X consecutive 1s and Y consecutive 0s (1 ≤ X, Y ≤ 10). As the number of arrangements can be very large, compute the answer with MODULO 109+
7 min read
Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1's
Given an integer N, the task is to count the number of binary strings possible of length N such that they don't contain "111" as a substring. The answer could be large so print answer modulo 109 + 7.Examples: Input: N = 3 Output: 7 All possible substring are "000", "001", "010", "011", "100", "101" and "110". "111" is not a valid string.Input N = 1
6 min read
Number of binary strings such that there is no substring of length ≥ 3
Given an integer N, the task is to count the number of binary strings possible such that there is no substring of length ? 3 of all 1's. This count can become very large so print the answer modulo 109 + 7.Examples: Input: N = 4 Output: 13 All possible valid strings are 0000, 0001, 0010, 0100, 1000, 0101, 0011, 1010, 1001, 0110, 1100, 1101 and 1011.
10 min read
Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
Generate all permutations of a given length such that every permutation has more or equals 1's than 0's in all prefixes of the permutation. Examples: Input: len = 4 Output: 1111 1110 1101 1100 1011 1010 Note that a permutation like 0101 can not be in output because there are more 0's from index 0 to 2 in this permutation. Input: len = 3 Output: 111
5 min read
Check if a binary string has two consecutive occurrences of one everywhere
Given string str consisting of only the characters 'a' and 'b', the task is to check whether the string is valid or not. In a valid string, every group of consecutive b must be of length 2 and must appear after 1 or more occurrences of character 'a' i.e. "abba" is a valid sub-string but "abbb" and aba are not. Print 1 if the string is valid, else p
6 min read
Check if a binary string contains consecutive same or not
Given a binary string str consisting of characters '0' and '1'. The task is to find whether the string is valid or not. A string is valid only if the characters are alternating i.e. no two consecutive characters are the same. Examples: Input: str[] = "010101" Output: Valid Input: str[] = "010010" Output: Invalid Approach: Start traversing the strin
4 min read
Check if any pair of consecutive 1s can be separated by at most M 0s by circular rotation of a Binary String
Given a binary string S of length N and a positive integer M, the task is to check if it is possible to rotate the string circularly any number of times such that any pair of consecutive 1s are separated by at most M 0s. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: S = "101001", M = 1Output: YesExplanation: Right shi
8 min read
Python program to check if the list contains three consecutive common numbers in Python
Our task is to print the element which occurs 3 consecutive times in a Python list. Example : Input : [4, 5, 5, 5, 3, 8] Output : 5 Input : [1, 1, 1, 64, 23, 64, 22, 22, 22] Output : 1, 22 Approach : Create a list.Create a loop for range size – 2.Check if the element is equal to the next element.Again check if the next element is equal to the next
3 min read
Count number of binary strings without consecutive 1’s : Set 2
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 = 5 Output: 5 Explanation: The non-negative integers <= 5 with their corresponding binary representations are: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 Among them, only 3 has two consecutiv
15+ min read
Practice Tags :
three90RightbarBannerImg