Skip to content
Discussion options

You must be logged in to vote

We need to find the number of paths from top-left to bottom-right in a matrix where the sum of elements along the path is divisible by k, moving only right or down.

Approach:

Problem Analysis

  • We can only move right or down
  • We need to track the sum modulo k for each path
  • The constraints are large (up to 50,000 cells) but k is small (≤ 50)

Dynamic Programming Approach

I'll use a 2D DP array where dp[j][r] represents the number of paths to current column j with remainder r.

Since we process row by row, I can optimize space by only storing the current and previous row information.

Let's implement this solution in PHP: 2435. Paths in Matrix Whose Sum Is Divisible by K

<?php
/**
 * @param Int…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Nov 26, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Nov 26, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested hard Difficulty
2 participants