Check if all the 1s in a binary string are equidistant or not in Python
Last Updated :
24 May, 2024
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: True
Explanation: The distance between all the 1’s is same and is equal to 1.
Input: “0101001”
Output: False
Explanation: The distance between the 1st and the 2nd 1’s is 2
and the distance between the 2nd and the 3rd 1’s is 3.
The base condition for this problem statement is, if there are less than 2 '1s in the string, return True. This means there is either no 1 or at most one 1 present, making all the 1s equidistant. And if there are two or more than two 1s present, we need to calculate the difference between each 1.
Check if all 1s in a Binary String are Equidistant
Now let us see the different approaches to check if all the 1s in a binary string are equidistant or not in Python.
Brute Force Approach
In this method, we use list comprehension to find the positions of all 1s in the string using enumerate() function. Compute and store the distance between the first two positions of 1s. Then iterate over the remaining positions of '1's starting from the third element of the list. Compare the distance between each pair of consecutive positions of 1s with the initial distance and if any pair has a different distance, return False. This means the one of the pair's distance is not equal to the others.
Example: In this example, using list comprehension we store the position of all the 1s of the string in a list. Then calculate the distance of first two element of the list. For the rest of the element we used for loop for iteration and checked if any one of the pair does not match the distance.
Python
def are_1s_equidistant(s):
# Find positions of 1s
positions = [i for i, char in enumerate(s) if char == '1']
# Check if less than 2 1s
if len(positions) < 2:
return True
# Calculate distance
distance = positions[1] - positions[0]
# Iterate over remaining 1s
for i in range(2, len(positions)):
# Compare distances
if positions[i] - positions[i - 1] != distance:
return False
return True
s = "100100100100100"
print(are_1s_equidistant(s))
Output:
True
Early Exit Strategy
This method, simply compare the distance between all the 1s in the string by initializing two variables to store previous index of 1 and the distance between two 1s to -1 and None respectively. Then iterating through the string with for loop and enumerate(), when a 1 is encountered, store its index and calculate the distance. If the current distance, that is the difference between the current index and previous index is unequal, return False, otherwise update previous index and distance. If loop completes, return True.
Example: Demonstration of Checking if all the 1s in a binary string are equidistant or not using Early Exit Strategy
Python
def are_1s_equidistant_early_exit(s):
# initialise previous index and distance
prev_index = -1
distance = None
# iterate over the string
for i, char in enumerate(s):
if char == '1':
# update previous index for the first occurence
if prev_index == -1:
prev_index = i
else:
# calculate current dustance
current_distance = i - prev_index
# update distance for the first occurence
if distance is None:
distance = current_distance
# compare distance with current distance
elif distance != current_distance:
return False
# update previous index
prev_index = i
return True
s = "1001001010100100"
print(are_1s_equidistant_early_exit(s))
Output:
False
Similar Reads
Python - Check if all elements in List are same To check if all items in list are same, we have multiple methods available in Python. Using SetUsing set() is the best method to check if all items are same in list. Pythona = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) OutputTrue Explanation:Converting
3 min read
Python | Check if all elements in a list are identical Given a list, write a Python program to check if all the elements in that list are identical using Python. Examples: Input : ['a', 'b', 'c'] Output : False Input : [1, 1, 1, 1] Output : TrueCheck if all elements in a list are identical or not using a loop Start a Python for loop and check if the f
5 min read
Techniques to Find Consecutive 1s or 0s in a Python String 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: TrueExplanation: the string have 2 consecutive 0s Input: str = â1000000001
4 min read
Python - Test if all elements in list are of same type When working with lists in Python, there are times when we need to ensure that all the elements in the list are of the same type or not. This is particularly useful in tasks like data analysis where uniformity is required for calculations. In this article, we will check several methods to perform th
2 min read
Python - Check if String contains any Number We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = "Hello123" since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = "HelloWorld" since it has no digits the output should
2 min read