File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number } n
3+ * @return {number }
4+ */
5+ var climbStairs = function ( n ) {
6+ if ( n <= 2 ) {
7+ return n ;
8+ }
9+
10+ let [ firstStair , secondStair ] = [ 1 , 2 ] ;
11+ let thirdStair ;
12+
13+ for ( let i = 3 ; i <= n ; i ++ ) {
14+ thirdStair = firstStair + secondStair ;
15+
16+ [ firstStair , secondStair ] = [ secondStair , thirdStair ] ;
17+ }
18+
19+ return thirdStair ;
20+ } ;
21+
22+ // Time Complexity: O(n)
23+ // Reason: The function uses a loop that iterates from 3 to n,
24+ // which means it runs in linear time with respect to n.
25+
26+ // Space Complexity: O(1)
27+ // Reason: The function uses a fixed amount of extra space
28+ // (a few integer variables: first, second, and third).
29+ // It does not use any additional data structures
30+ // that grow with the input size n.
You can’t perform that action at this time.
0 commit comments