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?