Skip to content

Commit d6e57fb

Browse files
committed
solve: climbing stairs
1 parent e938454 commit d6e57fb

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

climbing-stairs/evan.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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.

0 commit comments

Comments
 (0)