Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

How many binary strings of length 30 contain neither the substring "11" nor the substring "000"?

How many binary strings of length 30 contain neither the substring "11" nor the substring "000"?
n=30
dp={('0',1):1,('1',1):1}
for _ in range(n-1):
    nd={}
    for (c,r),v in dp.items():
        if c=='1':
            k=('0',1); nd[k]=nd.get(k,0)+v
        else:
            if r+1<=2: nd[('0',r+1)]=nd.get(('0',r+1),0)+v
            nd[('1',1)]=nd.get(('1',1),0)+v
    dp=nd
print(sum(dp.values()))
What is printed?
  1. A. 1346269
  2. B. 7739
  3. C. 2
  4. D. 5842

Correct answer: B. 7739

Track the last character and the length of the trailing zero run (at most two zeros), with every 1 forced to be followed by a 0. Dropping the 000 rule counts strings the question forbids, and a length off by one shifts the whole answer.

More Coding Interview Problems questions

Exams that ask this topic