Home > Blockchain >  Find substrings in binary string
Find substrings in binary string

Time:10-13

I am given string of 0s and 1s, and have to find distinct number of substrings such that:

  1. number of 0s and 1s should be same
  2. 1s should come after 0s.

So, for example given 001101 answer would be 2: 0011, 01 Any suggestions? I could not come up with solution

CodePudding user response:

How about just generating 01, 0011 and so on, checking whether each of them is in the given string, and then counting the number of such occurrences?

s = '001101'

substrings = [t for x in range(1, len(s) // 2   1) if (t := '0' * x   '1' * x) in s]
print(substrings, len(substrings)) # ['01', '0011'] 2

This uses list comprehension with "Walrus" operator (introduced in python 3.8).

  • Related