I was doing an online interview some days back and came across this task that we can reach the nth step by using only steps 1 or 2 or 3.
Updated Question: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.
This is my solution using dynamic programming. But during the interview, I saw that there were 6 hidden test cases that were failing.
public static long countWays(int n)
{
if(n==0 || n==1) return 1;
long[] res = new long[n + 1];
res[0] = 1;
res[1] = 1;
res[2] = 2;
for (int i = 3; i <= n; i++)
res[i] = res[i - 1] + res[i - 2]
+ res[i - 3];
return res[n];
}
During the interview, only 5 test cases were passing out of 11. The remaining 6 are hidden test cases.
The range for n is 0 to 10 power 8.
I was not able to understand where I was doing a mistake, already this code is in O(n) time complexity. Is there a better way to do this or am I missing something?
n
could be as large as 10^8, there is no way the correct result of the arithmetic you're doing would fit within along
, since the sequence grows exponentially. – Onieonionn
values. – Instrumentalismlong
then it is unsolvable, since the correct answer will generally not fit in along
value. Typically in such algorithm problems, you would be expected to output the result modulo some convenient large prime number, such as 10^9 + 7. – OnieonionThere is a classic method which involves solving the difference equation to
and remaining. Can you please refer me some tutorial where I can learn this concept, I want to solve this program. – Kiffib(n) + 1
. – Crossbreed