Search code examples
bitmathematical-expressions

Mathematical equation for number of valid sequences (having no two 1's together) of N-bit number


I have encountered this interview puzzle and want to know its accurate answer.

You can generate 2^n different binary sequence of a n-bit number. Among these sequences the sequence having two 1's together will be considered as invalid else valid.

For example for N=3 sequences can be:
000 -> v 
001 -> v
010 -> v
011 -> iv
100 -> v
101 -> v
110 -> iv
111 -> iv       So output should be: 5

So formulate the strategy(hint provided to me: f(n) in terms of f(n-1)) which can tell number of valid sequences a N-bit number can have.


Solution

  • Update

    It turns out to be

    Answer(n bits) = fibonacci(n+2), if fibonacci(0) = 0, and fibonacci(1) = 1


    Analysis

    1 bit

    0
    1
    

    2 bit

    00
    01
    --
    10
    11 // x
    

    Now you see, if a sequence ends with 1, it can only be further appended by 0.

    3 bit

    000
    001
    --
    010
    011 // x
    --
    100
    101
    

    In general, how many 0 and how many 1 in [n] bits

    f[1](0) = 1 = fibonacci(2) = fibonacci(1+1)
    f[1](1) = 1 = fibonacci(1) = fibonacci(1)
    f[n](0) = f[n-1](0) + f[n-1](1) = fibonacci(n+1)
    f[n](1) = f[n-1](0) = fibonacci(n)
    f[n] = f[n](0)+f[n](1) = fibonacci(n+1) + fibonacci(n) = fibonacci(n+2)
    
    fibonacci(0) = 0
    fibonacci(1) = 1
    fibonacci(2) = 1