Skip to main content

Climbing Stairs in Java and Python

Count the ways to climb stairs with one- and two-step moves using rolling dynamic programming in Java and Python.

Problem and input contract

The input is an integer n ≥ 0. Return the exact number of ordered move sequences that land on step n. For example, a move of one followed by a move of two differs from the reverse order.

n = 0 gives 1 (the empty sequence). n = 1 gives 1. n = 3 gives 3.

Worked example

For n = 3, the sequences are 1+1+1, 1+2 and 2+1.

There is one way to stand at step 0 and one way to reach step 1. Step 2 has two paths. Step 3 has three paths, because it can follow either of the two paths to step 2 or the one path to step 1.

How the solution works

A path ends with either a one-step or a two-step move. Adding the counts for those two preceding positions covers all paths exactly once. There is one empty path for zero stairs.

The two running counts are enough because each new value depends only on the previous two. Java uses BigInteger for exact results. Both versions perform O(n) additions and retain two counts, but the integers themselves grow with n.

Python solution

def climb_stairs(n):
    previous, current = 1, 1
    for _ in range(2, n + 1):
        previous, current = current, previous + current
    return current

Java solution

import java.math.BigInteger;
class Solution {
    static BigInteger climbStairs(int n) {
        BigInteger previous = BigInteger.ONE;
        BigInteger current = BigInteger.ONE;
        for (int step = 1; step < n; step++) {
            BigInteger next = previous.add(current);
            previous = current;
            current = next;
        }
        return current;
    }
}

Approaches and complexity

The recursive version adds the results for n − 1 and n − 2 and repeatedly solves the same subproblems. A table avoids recomputation using O(n) stored counts. Rolling dynamic programming needs just the two latest counts. The exact counts have Θ(n) bits near the end, so the implementation uses Θ(n²) bit operations for the additions and Θ(n) bits of working storage. Fast doubling is a follow-up for large inputs.

Approach comparison
ApproachTimeAuxiliary spaceAdvantageLimitationUse case
Naive recursionExponentialO(n) stackDirect recurrenceRepeats subproblemsSmall demonstrations
Rolling DPO(n) additionsΘ(n) bitsKeeps two countsLarge integers still growTypical interview solution

Common mistakes and interview follow-up

Starting with zero ways at step 0 breaks the recurrence. Use one empty sequence, and use arbitrary-precision integers when counts can exceed fixed-width types.

Related practice: Longest Palindromic Substring: Explained with Java and Python Code.

Comments

Popular posts from this blog

Minimum Window Substring: Efficient Algorithm for Finding the Shortest Substring

The Minimum Window Substring problem is a classic string manipulation challenge that tests our algorithmic skills. In this blog, we will explore an efficient solution to find the minimum window substring in a given string. We will provide implementation examples in both Java and Python, enabling you to grasp the concepts and apply them to your own coding projects.   Understanding the Problem: Given a string and a target pattern, our objective is to find the minimum window substring in the given string that contains all the characters of the target pattern. The minimum window substring refers to the shortest possible substring that satisfies this condition.   Approach: To solve the Minimum Window Substring problem, we can use the sliding window technique. This approach involves maintaining a window of characters in the string and adjusting its size based on certain conditions. The key steps of the algorithm are as follows: Create two pointers, left and right, to define the windo...

Longest Palindromic Substring: Explained with Java and Python Code

The Longest Palindromic Substring problem is a classic challenge in the realm of string manipulation. In this blog, we will delve into the intricacies of finding the longest palindromic substring in a given string. Through a step-by-step approach and illustrative examples, you will gain a comprehensive understanding of the problem and learn how to solve it efficiently.   Understanding the Problem: A palindrome is a string that reads the same forward and backward. The Longest Palindromic Substring problem requires finding the longest substring within a given string that is also a palindrome. Our goal is to determine the length of this substring and return the substring itself.   Approach: To solve the Longest Palindromic Substring problem, we can employ a dynamic programming approach or use the expanding around center technique. Here, we will explore the dynamic programming approach. Create a boolean table, dp, of size [n][n] (where n is the length of the input string) to store ...