The Number of Ways to Stay in the Same Place After Some Steps problem asks you to count the number of ways to take exactly steps steps on an array of length arrLen, starting and ending at index 0. Each step you can move left, right, or stay in place (within bounds). Return the count modulo 10^9+7. This hard coding problem uses 2D DP with careful space optimization.
Google asks this because it requires reasoning about reachable positions — after k steps, the maximum reachable index is min(steps/2, arrLen-1), which bounds the state space. The dynamic programming interview pattern with careful state space pruning is the core skill tested.
2D DP with state compression. dp[step][pos] = ways to be at position pos after step steps. Transition: dp[s][p] = dp[s-1][p] + dp[s-1][p-1] + dp[s-1][p+1] (stay, came from right, came from left). Key optimization: max reachable position = min(steps//2, arrLen-1). Use rolling array to reduce space. Answer: dp[steps][0].
steps=3, arrLen=2. Positions: 0 and 1. dp[0][0]=1. After step 1: dp[1][0]=1(stay)+1(from 1 but arrLen constraint)=1, dp[1][1]=1(from 0). After step 2: dp[2][0]=dp[1][0]+dp[1][1]=2, dp[2][1]=dp[1][0]+dp[1][1]=2. After step 3: dp[3][0]=dp[2][0]+dp[2][1]=4, dp[3][1]=dp[2][0]+dp[2][1]=4. Answer = dp[3][0] = 4.
p-1 and p+1.The key insight is that after k steps from position 0, you can never be beyond position k (or arrLen-1). This bounds the effective state space dramatically. Practice similar 1D random walk DP problems where position-bounding prunes the state space. The rolling array space optimization is standard for DP where only the previous row is needed.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Ways to Distribute Candies | Hard | Solve | |
| Student Attendance Record II | Hard | Solve | |
| Race Car | Hard | Solve | |
| K Inverse Pairs Array | Hard | Solve | |
| Painting a Grid With Three Different Colors | Hard | Solve |