Wednesday, March 7, 2012

Calculate Number of Different Ways to Climb a Stairway with Constant Space and Linear Time

Problem: There are three ways to climb a stair, you can climb 1 step, 2 steps or 3 steps each time. Given a n step stairway, how many of ways can you climb up to the top?

Solution: As known, this is a simple DP problem.  If we can maintain an array dp[] with dp[i] representing the different ways to climb up i steps, we can get the final result in O(N). However, we need O(N) space as well. But actually, since dp[i] = dp[i-1] + dp[i-2] + dp[i-3], we don't need O(N) space, instead, we just need a cache with size 3. Then we can have a space complexity O(1) algorithm:

int climb_stair(int n)
{
  int cache[3];
  cache[0] = 1; /*ways to climb 0 step */
  cache[1] = 1; /*ways to climb 1 step */
  cach2[2] = 2; /*ways to climb 2 steps */

  if(n<=2) return cache[n];

  for(int i=3; i<=n; i++)
  {
     cache[i%3] = cache[0]+cache[1]+cache[2];
  }

  return cache[i%3];

}

Similarly, we can have a O(1) space algorithm for Fibonacci numbers.

3 comments:

  1. Actually, the recurrence relation for Fibonacci numbers has analytical solution, so it can be solved in constant time as well.

    ReplyDelete
  2. Hi,

    sorry for necroing :) linear recurrences' nth term (such as this one or the Fibonacci etc) can be computed in constant space and *O(logn)* time by iterated matrix powering. Just my 2cents :)

    ReplyDelete
  3. Hi Szaboic,
    You are right. Thanks for your comments. Besides, Onur is also right. We even have a constant time solution here. My original post just gave the common solution:)

    ReplyDelete