Given a binary digit count of n, and a maximum consecutive occurrence count of m, find the number of different possible binary numbers. Also, the leftmost and rightmost bit must be 1.
For example n = 5, and m = 3.
The count is 7:
10001
10011
10101
10111
11001
11011
11101
Notice we excluded 11111 because too many consecutive 1’s exist in it.
This was an interview question I had recently, and It has been bothering me. I don’t want to brute force check each number for legitimacy because n can be > 32.
Let’s call a binary sequence almost valid if it starts with “1” and has at most
mconsecutive “1” digits.For
i = 1, ..., nandj = 0, ..., mleta(i, j)be the number of almost valid sequences with lengthithat end with exactlyjconsecutive “1” digits.Then
a(1, 1) = 1anda(1, j) = 0 for j != 1, because “1” is the only almost valid sequence of length one.n >= 2andj = 0we havea(i, 0) = a(i-1, 0) + a(i-1, 1) + ... + a(i-1, m), because appending “0” to any almost valid sequence of lengthi-1gives an almost valid sequence of lengthiending with “0”.n >= 2andj > 0we havea(i, j) = a(i-1, j-1)because appending “1” to an almost valid sequence withi-1trailing ones gives an almost valid sequence of lengthjwithitrailing ones.Finally, the wanted number is the number of almost valid sequences with length
nthat have a trailing “1”, so this isWritten as a C function:
The storage requirement could even be improved, because only the last column of the matrix
ais needed. The runtime complexity isO(n*m).