Min Cost Climbing Stairs

Algorithms
Easy
Spotify
43.7K views

You are given an integer array `cost` where `cost[i]` is the cost to step on the $i$-th stair. You can either start at index 0 or index 1. Find the minimum cost to reach the top of the floor. Use DP.

Why Interviewers Ask This

Spotify asks this to evaluate your ability to identify overlapping subproblems and apply dynamic programming efficiently. They want to see if you can recognize that the optimal path to any stair depends only on the previous two states, allowing you to optimize space complexity from O(n) to O(1). This tests your core algorithmic thinking and code optimization skills under pressure.

How to Answer This Question

1. Clarify constraints: Confirm if the array is empty or if costs are non-negative. 2. Define the state: Explicitly state that dp[i] represents the minimum cost to reach step i. 3. Establish the recurrence relation: Explain that reaching step i requires coming from either i-1 or i-2, so dp[i] = min(dp[i-1], dp[i-2]) + cost[i]. 4. Handle base cases: Note that you can start at index 0 or 1, meaning the cost to reach those steps is just their respective costs. 5. Optimize space: Propose using two variables instead of an array since you only need the last two values. 6. Walk through a trace: Use a small example like [10, 15, 20] to demonstrate how the logic flows step-by-step before coding.

Key Points to Cover

  • Explicitly defining the recurrence relation as min(prev, prev2) + current_cost
  • Recognizing the base cases allow starting at either index 0 or 1
  • Optimizing space complexity from O(n) to O(1) using two variables
  • Correctly identifying that the final answer is the min of the last two calculated values
  • Demonstrating a clear thought process through a manual trace of the example

Sample Answer

To solve the Min Cost Climbing Stairs problem, I would first clarify the input constraints, ensuring we handle edge cases like an empty array. My approach relies on Dynamic Programming because the optimal solution for an…

Common Mistakes to Avoid

  • Failing to realize the final step doesn't require adding the cost of a non-existent top floor
  • Using an O(n) space array when interviewers expect O(1) space optimization
  • Incorrectly setting base cases by ignoring that one can start at index 1 without paying index 0's cost
  • Confusing the cost to reach a step versus the cost to climb off a step

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 30 Spotify questions