title: Time and space complexity of dynamic programming algorithm
body: <p>This algorithm is from Cracking the Coding Interview, 5th Edition, found here: <a href="https://www.geekbooks.me/book/view/cracking-the-coding-interview-5th-edition" rel="nofollow noreferrer">https://www.geekbooks.me/book/view/cracking-the-coding-interview-5th-edition</a> </p>
  
  <p>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.
  Algorithm:</p>
  
  <pre><code> public static int countWaysDP(int n, int[] map) {
      if (n &lt; 0) {
          return 0;
      } else if (n == 0) {
          return 1;
      } else if (map[n] &gt; -1) {
          return map[n];
      } else {
          map[n] = countWaysDP(n - 1, map) + 
                   countWaysDP(n - 2, map) + 
                   countWaysDP(n - 3, map);
          return map[n];
          }
  }
  </code></pre>
  
  <p>What is the time and space complexity of this algorithm?  I think since memoization is used, the results are stored so values don't get calculated multiple times like in the pure recursive method.  Since there are three calls to countWaysDP the time complexity is O(3n) which is an element of O(n).  The space complexity would be O(n+n) one n for the size of map and one n for the recursive call stack, which is also an element of O(n).  Is my reasoning correct?</p>
  
  <p>Thanks</p>