Problem Links
Author: Ankur Goel
Tester: Ankur Goel
Editorialist: Ankur Goel
Difficulty
Medium
Prerequisites
Fibonacci Series, Recursion
Problem
The King wants to select N common folks as solider from the Fire and Ice island in order to win the battle. He can only select odd number of people from land of fire or ice only in one go.He cannot select bunch of people consecutively from either territory.Find the number of ways the mad king could select his army.
Note :The number of people in each territory is infinite.
Quick Explanation
Ans= 2*Fibo(N)%M
Explanation
The Problem is simply based on the Fibonacci Series. Let 0 denotes the people from Land of Ice and 1 denotes the people from Land of Fire then, the number of binary strings of length n without an even number of consecutive 0s or 1s is 2Fn. For example, out of the 16 binary strings of length 4, there are 2F4 = 6 without an even number of consecutive 0s or 1s – they are 0001, 0111, 0101, 1000, 1010, 1110.
Find the Fibonacci using O(Log N) Algorithm and take the modulo M at every step, otherwise your algo may fail due to Time Complexity or due to the Overflow of Fibonacci Number beyond the range of even 64 bit int.
Author's Solution
Author’s solution can be found here