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?- A. 1346269
- B. 7739
- C. 2
- 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
- How many primes p satisfy p ≤ 1,000,000 and p ≡ 3 (mod 4)? python N=106 s=bytearray([1])(N+1); s[0]=0; s[1]=0 for i in…
- The recursive extended Euclidean algorithm eg(a, b) returns (g, x, y) with a·x + b·y = g, using eg(a, b) = (g, y, x − (a//b)·y) when b ≠ 0…
- Matrix chain: matrices A1..A6 have dimension sequence p = [30, 35, 15, 5, 10, 20, 25] (Ai is p[i−1] × p[i]). What is the minimum number of…
- Game of two eggs and 100 floors: you have two identical eggs and must find the highest floor from which a dropped egg survives, using as…
- Array b = [9, 2, 7, 4, 1, 8, 3]. Count the pairs (i < j) with b[i] > 2·b[j] (a reverse pair). Run the brute-force code. python…
- For the array c = [1, 2, 3, 4], consider every non-empty subarray and its XOR value. How many subarrays have an XOR value that is strictly…