Climbing stairs and house robber
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Climbing stairs and house robber form the foundational patterns for state transitions across linear and circular arrays.
Counting ways versus minimizing cost on stairs
Climbing stairs and minimum cost climbing share identical state graphs with different algebraic operators. When counting ways, decisions combine using addition because distinct movement paths are mutually exclusive. Reaching stair i equals the sum of ways reaching i - 1 and i - 2.
Step by step
Step 1 of 4
- step
- 2
- ways
- 2
Example 1 · Climbing Stairs, Plain Recursion: O(2^n) Time, O(n) Stack
public class StairsRecursion { static int calls = 0;
public static int ways(int n) { calls++; if (n <= 2) return n; return ways(n - 1) + ways(n - 2); }
public static void main(String[] args) { System.out.println("Ways for 5: " + ways(5)); System.out.println("Calls for 5: " + calls); calls = 0; System.out.println("Ways for 20: " + ways(20)); System.out.println("Calls for 20: " + calls); }}Ways for 5: 8 Calls for 5: 9 Ways for 20: 10946 Calls for 20: 13529
What this code does
- Every call splits into two more calls, so the number of calls roughly doubles each time n grows by 1.
- The same small steps are solved again and again: for n = 20 the program makes 13,529 calls to find one number.
- It is correct but far too slow beyond n of about 40.
Example 2 · Climbing Stairs, Memoization: O(n) Time, O(n) Space
public class StairsMemo { static int calls = 0;
public static int ways(int n, int[] memo) { calls++; if (n <= 2) return n; if (memo[n] != 0) return memo[n]; memo[n] = ways(n - 1, memo) + ways(n - 2, memo); return memo[n]; }
public static void main(String[] args) { System.out.println("Ways for 20: " + ways(20, new int[21])); System.out.println("Calls for 20: " + calls); calls = 0; System.out.println("Ways for 40: " + ways(40, new int[41])); System.out.println("Calls for 40: " + calls); }}Ways for 20: 10946 Calls for 20: 37 Ways for 40: 165580141 Calls for 40: 77
What this code does
- memo[n] remembers the answer for step n, so the second request for it returns at once instead of recursing.
- There are only n different steps, so each is solved once: 37 calls for n = 20 instead of 13,529.
- The price is O(n) memory for memo and O(n) call-stack depth.
Example 3 · Climbing Stairs, Tabulation: O(n) Time, O(n) Space
public class StairsTable { public static int ways(int n) { if (n <= 2) return n; int[] dp = new int[n + 1]; dp[1] = 1; dp[2] = 2; for (int i = 3; i <= n; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[n]; }
public static void main(String[] args) { System.out.println("Ways for 5: " + ways(5)); System.out.println("Ways for 20: " + ways(20)); System.out.println("Ways for 40: " + ways(40)); }}Ways for 5: 8 Ways for 20: 10946 Ways for 40: 165580141
What this code does
- dp[i] depends only on dp[i - 1] and dp[i - 2], which are already filled when the loop reaches i.
- The loop runs n - 2 times, so time is O(n) with no call-stack depth and no risk of stack overflow.
- The table still takes O(n) memory.
Example 4 · Climbing Stairs, Two Variables: O(n) Time, O(1) Space
public class StairsRolling { public static int ways(int n) { if (n <= 2) return n; int prev2 = 1; int prev1 = 2; for (int i = 3; i <= n; i++) { int current = prev1 + prev2; prev2 = prev1; prev1 = current; } return prev1; }
public static void main(String[] args) { System.out.println("Ways for 5: " + ways(5)); System.out.println("Ways for 20: " + ways(20)); System.out.println("Ways for 40: " + ways(40)); }}Ways for 5: 8 Ways for 20: 10946 Ways for 40: 165580141
What this code does
- Each step reads only the two answers just before it, so older cells can be forgotten.
- prev2 and prev1 slide forward one step per loop pass, so memory drops from O(n) to O(1).
- The answers are identical to the table version; only the memory changes.
Example 5 · Climbing Stairs with Up to k Steps: O(n x k) Time, O(n) Space
public class ClimbingStairsKSteps { public static int countWaysK(int n, int k) { int[] dp = new int[n + 1]; dp[0] = 1; for (int i = 1; i <= n; i++) { for (int step = 1; step <= k; step++) { if (i - step >= 0) { dp[i] += dp[i - step]; } } } return dp[n]; }
public static void main(String[] args) { System.out.println("Ways for n=4, k=2: " + countWaysK(4, 2)); System.out.println("Ways for n=4, k=3: " + countWaysK(4, 3)); System.out.println("Ways for n=5, k=3: " + countWaysK(5, 3)); }}Ways for n=4, k=2: 5 Ways for n=4, k=3: 7 Ways for n=5, k=3: 13
What this code does
- State dp[i] sums ways to land on step i from all valid prior steps up to k back.
- Base case dp[0] equals 1, representing a single way to remain at the ground floor.
- Increasing maximum jump size k expands total reachable path permutations.
When optimizing cost, decisions combine using a min function. Reaching stair i selects the cheaper expenditure between stepping from i - 1 and i - 2. Both problems generalize naturally to k steps through an inner loop over step sizes. Notice that each state depends only on the immediately preceding two cells. This dependency structure allows replacing full arrays with two rolling variables. Rolling variables reduce memory footprint from O(n) to constant O(1) space.
House Robber: Non-adjacent element optimization
The House Robber problem introduces adjacency exclusion constraints across linear arrays. You cannot rob two consecutive houses without triggering security alarms. At house i, you either rob house i or skip house i.
Example 6 · House Robber Non-Adjacent Selection
public class HouseRobberLinear { public static int rob(int[] nums) { if (nums == null || nums.length == 0) return 0; int prev2 = 0; int prev1 = 0; for (int num : nums) { int current = Math.max(prev1, prev2 + num); prev2 = prev1; prev1 = current; } return prev1; }
public static void main(String[] args) { int[] h1 = {1, 2, 3, 1}; System.out.println("Loot 1: " + rob(h1)); int[] h2 = {2, 7, 9, 3, 1}; System.out.println("Loot 2: " + rob(h2)); }}Loot 1: 4 Loot 2: 12
What this code does
- Variable prev1 stores the optimal answer up to the previous house.
- Variable prev2 stores the optimal answer up to two houses prior.
- Running with two rolling variables avoids allocating an auxiliary array.
If you rob house i, you collect its value plus the optimal loot from house i - 2. If you skip house i, you carry forward the optimal loot from house i - 1. The recurrence takes the maximum between these two competing choices. Base cases are direct: zero houses yield zero, and one house yields that house's value. Since transitions reference only two preceding values, two variables suffice for execution. This achieves optimal O(n) time and O(1) auxiliary space.
Handling circular arrays in House Robber II
In House Robber II, houses arrange in a circle where the first and last houses neighbor each other. Robbing house 0 directly prohibits robbing house n - 1. This circular dependency creates a cyclic constraint that breaks standard linear ordering.
Example 7 · House Robber II Circular Street
public class HouseRobberCircular { private static int robLinear(int[] nums, int start, int end) { int prev2 = 0; int prev1 = 0; for (int i = start; i <= end; i++) { int current = Math.max(prev1, prev2 + nums[i]); prev2 = prev1; prev1 = current; } return prev1; }
public static int rob(int[] nums) { if (nums == null || nums.length == 0) return 0; int n = nums.length; if (n == 1) return nums[0]; int case1 = robLinear(nums, 0, n - 2); int case2 = robLinear(nums, 1, n - 1); return Math.max(case1, case2); }
public static void main(String[] args) { int[] h1 = {2, 3, 2}; System.out.println("Circular loot 1: " + rob(h1)); int[] h2 = {1, 2, 3, 1}; System.out.println("Circular loot 2: " + rob(h2)); int[] h3 = {1, 2, 3}; System.out.println("Circular loot 3: " + rob(h3)); }}Circular loot 1: 3 Circular loot 2: 4 Circular loot 3: 3
What this code does
- The circular layout means house 0 and house n - 1 cannot both be robbed.
- Case 1 scans houses 0 to n - 2. Case 2 scans houses 1 to n - 1.
- The maximum of both linear evaluations yields the globally optimal answer.
Instead of tracking complex boolean flags, decompose the circle into two independent linear subproblems. In subproblem one, consider houses from index 0 to n - 2, guaranteeing the last house is untouched. In subproblem two, consider houses from index 1 to n - 1, guaranteeing the first house is untouched. Run standard linear House Robber on both slices independently. The overall answer is simply the maximum between both subproblem results. Decomposition into disjoint linear cases is a powerful strategy for circular dynamic programming.
Next step
Check your understanding
10 quick questions