githubEdit

08. Number of Paths in a Matrix with K Coins

βœ… GFG solution to the Number of Paths in a Matrix with K Coins problem: count paths from top-left to bottom-right collecting exactly k coins using optimized dynamic programming. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

You are given a matrix mat[][] of size n x m, where each cell contains some coins. Your task is to count the number of ways to collect exactly k coins while moving from the top-left cell to the bottom-right cell.

From a cell (i, j), you can only move to:

  • Cell (i+1, j) (down)

  • Cell (i, j+1) (right)

πŸ“˜ Examples

Example 1

Input: k = 12, mat[][] = [[1, 2, 3],
                          [4, 6, 5],
                          [3, 2, 1]]
Output: 2
Explanation: There are 2 possible paths with exactly 12 coins:
- Path 1: 1 + 2 + 6 + 2 + 1 = 12
- Path 2: 1 + 2 + 3 + 5 + 1 = 12

Example 2

πŸ”’ Constraints

  • $1 \le k \le 100$

  • $1 \le n, m \le 100$

  • $0 \le \text{mat}[i][j] \le 200$

βœ… My Approach

The optimal approach uses Dynamic Programming with Space Optimization to efficiently count paths while tracking coin sums:

2D Row-Optimized DP

  1. State Definition:

    • dp[j][s] = number of ways to reach column j in current row with sum s

    • We only need to track the previous row, not the entire matrix history

  2. Initialization:

    • Start at (0, 0) with mat[0][0] coins

    • Initialize first row by moving right, accumulating coins

  3. Row-by-Row Processing:

    • For each new row, create a fresh DP table

    • For each cell (i, j):

      • Can reach from left: ndp[j-1][s - mat[i][j]]

      • Can reach from top: dp[j][s - mat[i][j]]

    • Sum both contributions for total paths to (i, j) with sum s

  4. Space Optimization:

    • Only maintain DP arrays for current and previous row

    • Reduces space from O(n Γ— m Γ— k) to O(m Γ— k)

  5. Result Extraction:

    • Return dp[m-1][k] = paths reaching bottom-right with exactly k coins

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n Γ— m Γ— k), where n and m are matrix dimensions and k is the target sum. For each of the n Γ— m cells, we iterate through all possible sums up to k to compute the number of paths.

  • Expected Auxiliary Space Complexity: O(m Γ— k), as we maintain only two rows of the DP table at any time (current and previous row), each storing states for m columns and k+1 possible sums. This is a significant optimization over the naive O(n Γ— m Γ— k) space approach.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Standard 3D DP Approach

πŸ’‘ Algorithm Steps:

  1. Create DP table indexed by position and current sum.

  2. Base case: starting cell has one path with its value if within k.

  3. For each cell, add ways from top and left positions.

  4. Return count of paths ending at bottom-right with sum k.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n Γ— m Γ— k) - Iterate through all states

  • Auxiliary Space: πŸ’Ύ O(n Γ— m Γ— k) - Full 3D array

βœ… Why This Approach?

  • Most intuitive DP formulation

  • Clear state representation

  • Easy to debug and verify

πŸ“Š 3️⃣ DFS with Memoization

πŸ’‘ Algorithm Steps:

  1. Recursively explore paths from start to end.

  2. Track current position and accumulated sum.

  3. Cache results to avoid recomputation.

  4. Count valid paths reaching target with sum k.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n Γ— m Γ— k) - Each state visited once

  • Auxiliary Space: πŸ’Ύ O(n Γ— m Γ— k) - Memoization map and stack

βœ… Why This Approach?

  • Natural problem decomposition

  • Flexible for variations

  • Good for understanding recursion

πŸ“Š 4️⃣ Bottom-Up Iterative DP

πŸ’‘ Algorithm Steps:

  1. Build solution from top-left to bottom-right.

  2. For each cell and sum, compute ways to reach it.

  3. Combine paths from top cell and left cell.

  4. Extract final answer for target position and sum.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n Γ— m Γ— k) - Triple nested loops

  • Auxiliary Space: πŸ’Ύ O(n Γ— m Γ— k) - 3D DP array

βœ… Why This Approach?

  • Standard DP pattern

  • No recursion overhead

  • Clear forward progression

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🏷️ 2D Row Optimization

🟒 O(n Γ— m Γ— k)

🟒 O(m Γ— k)

πŸš€ Good space-time balance

πŸ”§ Moderate complexity

πŸ” Standard 3D DP

🟒 O(n Γ— m Γ— k)

πŸ”΄ O(n Γ— m Γ— k)

πŸ“– Most straightforward

πŸ’Ύ High memory usage

πŸ“Š DFS Memoization

🟒 O(n Γ— m Γ— k)

πŸ”΄ O(n Γ— m Γ— k)

🎯 Intuitive recursion

🐌 Stack overhead

πŸ”„ Bottom-Up DP

🟒 O(n Γ— m Γ— k)

πŸ”΄ O(n Γ— m Γ— k)

⭐ No recursion

πŸ’Ύ Full space requirement

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Production code

πŸ₯‡ 2D Row Optimization

β˜…β˜…β˜…β˜…β˜…

πŸ“– Learning/Teaching

πŸ₯ˆ Standard 3D DP

β˜…β˜…β˜…β˜…β˜…

πŸ”§ Interview discussion

πŸ₯‰ DFS Memoization

β˜…β˜…β˜…β˜…β˜†

🎯 Contest/Speed coding

πŸ… Bottom-Up DP

β˜…β˜…β˜…β˜…β˜†

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated