1

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.

pankiii
  • 435
  • 3
  • 9

1 Answers1

2

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
Community
  • 1
  • 1
Dante May Code
  • 11,177
  • 9
  • 49
  • 81
  • take n=1: f(3) = f(2) + f(1) = 2*f(1) + f(0) = 2 (right)` but if we take n=2: `f(4) = f(3) + f(2) = 2*f(2) + f(1) = 4+1 = 5` shouldn't this be 3??? – pankiii Jun 23 '11 at 07:50
  • 1
    @pankiii, f(0) = 0, f(1) = 1, f(2) = 1, f(3) = 2, f(4) = 3. Why do you take f(2) = 2? – Dante May Code Jun 23 '11 at 07:57
  • :( Yes I have messed up f(2) with n=1 outcome...sorry for that; yes f(2) = 1, and 2:F(4)=f(3)+f(2)=2+1 = 3 ...The solution is great and logical.- Thanks – pankiii Jun 23 '11 at 08:13