logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

70. Climbing Stairs

1 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

At any step, you can climb either 1 step or 2 steps. So, the number of ways to reach step n is the sum of:

  • The number of ways to reach step n - 1 (and then take 1 step)
  • The number of ways to reach step n - 2 (and then take 2 steps)

This is structurally identical to the Fibonacci sequence.

# Complexity

Space ComplexityTime Complexity
O(N)\text{O}(N)O(N)O(n)\text{O}(n)O(n)

# Code

// Memoization array to cache results
int[] memo;
 
// Recursive helper function to count ways to climb to step n
int countWays(int step) {
    // Base case: only 1 way to reach the first step
    if (step == 1) return 1;
 
    // Base case: two ways to reach the second step (1+1 or 2)
    if (step == 2) return 2;
 
    // Return cached result if already computed
    if (memo[step] != -1) return memo[step];
 
    // Compute the result recursively and store it
    memo[step] = countWays(step - 1) + countWays(step - 2);
 
    return memo[step];
}
 
public int climbStairs(int n) {
    // Initialize memo array with -1 to indicate uncomputed values
    memo = new int[46];
    Arrays.fill(memo, -1);
 
    // Compute and return the number of ways to climb n stairs
    return countWays(n);
}
 
←Previous69. Sqrt(x)Next→88. Merge Sorted Array (In-Place)

On this page

IntuitionComplexityCode