Given that a coin is tossed N times. The task is to find the total number of the sequence of tosses such that after the first head from left, all the alternating positions to the right of it are occupied by the head only. The positions except the alternating position can be occupied by any of head or tail.
For example, if you are tossing a coin 10 times (N = 10) and the first head occurs at the 3rd position, then all the further alternating positions to the right are 5, 7, 9…
Input: N = 2
All possible combinations will be TT, TH, HT, HH.
Input: N = 3
All possible combinations will be TTT, TTH, THT, THH, HTH, HHH.
In this case, HHT & HTT is not possible because in this combination
the condition of alternate heads does not satisfy. Hence, the answer will be 6.
If the sequence is to start with a tail, then all possible sequences of length N-1 are valid. Now, if the sequence is to start with a head, then every odd index in the sequence (assuming the sequence is 1-based) will be head, and the rest of the N/2 places can be either head or tail. Thus, the recursive formula for the above problem will be:
f(N) = f(N-1) + 2floor(N/2)
Let fo(N) and fe(N) be the functions that are defined for the odd and even values of N respectively. fo(N) = fe(N-1) + 2(N-1)/2 fe(N) = fo(N-1) + 2N/2 From above equation compute fo(N) = fo(N-2) + 2(N-1)/2 + 2(N-1)/2 fe(N) = fe(N-2) + 2N/2 + 2(N-2)/2 Base Case: fo(1) = 2 fe(0) = 1 By using the above equation, compute the following results : fo(N) - fo(N-2) = 2(N-1)/2 + 2(N-1)/2 fo(N) - fo(N-2) = 2(N+1)/2 By taking the sum of above equation for all odd values of N, below thing is computed. fo(N) - fo(N-2) + fo(N-1) - fo(N-3) + ...... + fo(3) - fo(1) = 22 + 23 + 24 + ..... + 2(N+1)/2 Hence on summation, fo(N) - fo(1) = SUM[ n = 0 to (N+1)/2 ] 2n - 21 - 20 By using sum of geometric progression fo(N) = 2( N + 1 ) / 2 + 2( N + 1 ) / 2 - 2 Similarly, find fe(N) : fe(N) = fe(N-2) + 2N/2 + 2(N-2)/2 fe(N) - fe(0) = SUM[ n = 0 to N/2 ] 2n - 20 - SUM[ n = 0 to (N-1)/2 ] 2n By using sum of geometric progression fe(N) = 2 (N / 2) + 1 + 2 N / 2 - 2
The final formula will be as follows:
f(N) = 2(N+1)/2 + 2(N+1)/2 – 2, if N is odd
f(N) = 2(N/2) + 1 + 2N/2 – 2, if N is even
Below is the implementation of the above approach:
Time Complexity: O(LogN)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.