Manhattan Distances of All Arrangements of Pieces
HardPrompt
You are given three integers m, n, and k.
There is a rectangular grid of size m × n containing k identical pieces. Return the sum of Manhattan distances between every pair of pieces over all valid arrangements of pieces.
A valid arrangement is a placement of all k pieces on the grid with at most one piece per cell.
Since the answer may be very large, return it modulo 109 + 7.
The Manhattan Distance between two cells (xi, yi) and (xj, yj) is |xi - xj| + |yi - yj|.
Example 1:
Input: m = 2, n = 2, k = 2
Output: 8
Explanation:
The valid arrangements of pieces on the board are:

- In the first 4 arrangements, the Manhattan distance between the two pieces is 1.
- In the last 2 arrangements, the Manhattan distance between the two pieces is 2.
Thus, the total Manhattan distance across all valid arrangements is 1 + 1 + 1 + 1 + 2 + 2 = 8.
Example 2:
Input: m = 1, n = 4, k = 3
Output: 20
Explanation:
The valid arrangements of pieces on the board are:

- The first and last arrangements have a total Manhattan distance of
1 + 1 + 2 = 4. - The middle two arrangements have a total Manhattan distance of
1 + 2 + 3 = 6.
The total Manhattan distance between all pairs of pieces across all arrangements is 4 + 6 + 6 + 4 = 20.
Constraints:
1 <= m, n <= 1052 <= m * n <= 1052 <= k <= m * n
Approaches
3 approaches with complexity analysis and trade-offs.
This approach directly simulates the process of finding the sum of Manhattan distances. It iterates through all possible pairs of distinct cells on the grid, calculates the Manhattan distance for each pair, and sums them up. This sum represents the total distance for a single arrangement where pieces occupy those two specific cells. By the principle of linearity and symmetry, we can find the total sum over all arrangements by multiplying this sum by the number of ways to place the remaining k-2 pieces, which is C(m*n - 2, k - 2).
Algorithm
- Calculate
N = m * n, the total number of cells. - If
k < 2, return 0 as no pairs of pieces can be formed. - Initialize a variable
total_dist_sumto store the sum of Manhattan distances between all pairs of distinct cells. - Use four nested loops to iterate through every possible pair of distinct cells
(r1, c1)and(r2, c2)on them x ngrid. - For each pair, calculate the Manhattan distance
|r1 - r2| + |c1 - c2|and add it tototal_dist_sum. - Since each pair is counted twice in the loops (e.g.,
(c1, c2)and(c2, c1)), dividetotal_dist_sumby 2. - Precompute factorials and their modular inverses to calculate combinations efficiently.
- Calculate the number of ways to place the remaining
k-2pieces in the remainingN-2cells, which isC(N-2, k-2). - The final answer is
(total_dist_sum * C(N-2, k-2)) % MOD.
Walkthrough
The core idea is to calculate the sum of Manhattan distances between every pair of distinct cells on the grid, let's call it Sum_Dist_Cells. The final answer is then Sum_Dist_Cells multiplied by the number of ways to choose the other k-2 pieces from the remaining m*n - 2 cells.
-
Step 1: Sum of Distances Between All Cell Pairs We can use four nested loops to iterate through all pairs of cells
c1 = (r1, c1)andc2 = (r2, c2). For each pair wherec1 != c2, we add|r1 - r2| + |c1 - c2|to a running total. To avoid double-counting, we can divide the final sum by 2. -
Step 2: Count Arrangements For any given pair of cells
c1andc2, if we place pieces on them, we still need to placek-2more pieces on the grid. The number of available cells ism*n - 2. The number of ways to do this is given by the binomial coefficientC(m*n - 2, k - 2). -
Step 3: Final Calculation The total sum over all arrangements is
(Sum_Dist_Cells * C(m*n - 2, k - 2)) % MOD.
Here is a conceptual code snippet for calculating Sum_Dist_Cells:
// This approach is too slow and will time out.// It's for conceptual understanding.long totalDist = 0;long N = (long)m * n;long MOD = 1_000_000_007; for (int r1 = 0; r1 < m; r1++) { for (int c1 = 0; c1 < n; c1++) { for (int r2 = 0; r2 < m; r2++) { for (int c2 = 0; c2 < n; c2++) { if (r1 == r2 && c1 == c2) continue; totalDist = (totalDist + Math.abs(r1 - r2) + Math.abs(c1 - c2)); } } }} // Each pair is counted twice, so divide by 2// In modular arithmetic, we multiply by the modular inverse of 2.long inv2 = power(2, MOD - 2); // Assuming a modular exponentiation function 'power'totalDist = (totalDist * inv2) % MOD; // Precompute factorials and their inverses to calculate combinationsprecomputeFactorials((int)N);long combinations = nCr_mod_p(N - 2, k - 2); // Assuming a combination function 'nCr_mod_p' long ans = (totalDist * combinations) % MOD;Complexity
Time
O((m*n)^2) due to the four nested loops iterating over all pairs of cells. Given `m*n <= 10^5`, this is approximately `10^10` operations, which is too slow.
Space
O(m*n) to store precomputed factorials for calculating combinations.
Trade-offs
Pros
Simple to understand and implement.
Directly follows from the problem's definition by reframing the summation.
Cons
Extremely inefficient due to its
O((m*n)^2)time complexity.Will result in a 'Time Limit Exceeded' error for the given constraints.
This approach improves upon the brute-force method by optimizing the calculation of the total distance sum between all cell pairs. Instead of iterating through all (m*n)^2 pairs of cells, we can separate the calculation for x-distances (rows) and y-distances (columns). The sum of x-distances can be found by considering pairs of rows, and the sum of y-distances by considering pairs of columns. This reduces the complexity but is still not efficient enough.
Algorithm
- The total sum is
C(N-2, k-2) * (SumX + SumY), whereN = m*n. SumXis the sum of row differences|r1 - r2|over all distinct cell pairs, andSumYis for column differences.SumXcan be expressed asn^2 * (sum of |i-j| for all pairs of rows i, j).- Calculate
sum_diff_m = Sum_{0 <= i < j < m} (j-i)using two nested loops, which takesO(m^2)time. - Then
SumX = n^2 * sum_diff_m. - Similarly, calculate
sum_diff_n = Sum_{0 <= i < j < n} (j-i)inO(n^2)time. - Then
SumY = m^2 * sum_diff_n. - Combine the results and multiply by
C(N-2, k-2).
Walkthrough
We build upon the insight that the total sum is C(N-2, k-2) * (SumX + SumY), where SumX and SumY are the sums of absolute differences of row and column indices, respectively, over all pairs of distinct cells.
-
Calculating
SumXThe sumSumX = Sum_{c1 != c2} |r1 - r2|. A pair of cells from rowsiandjcontributes|i-j|to this sum. For any two distinct rowsiandj, there arencells in each, formingn*npairs of cells. Thus, the total contribution from these two rows isn^2 * |i-j|.SumX = Sum_{0 <= i < j < m} n^2 * (j-i). We can calculateSum_{0 <= i < j < m} (j-i)with nested loops. -
Calculating
SumYSymmetrically,SumY = Sum_{0 <= i < j < n} m^2 * (j-i). -
Complexity Calculating the sum of differences for rows takes
O(m^2)and for columns takesO(n^2). Precomputing factorials takesO(m*n). The total time complexity isO(m*n + m^2 + n^2).
Example code snippet for this logic:
long N = (long)m * n;long MOD = 1_000_000_007; // Calculate SumXlong sum_diff_m = 0;for (long i = 0; i < m; i++) { for (long j = i + 1; j < m; j++) { sum_diff_m = (sum_diff_m + (j - i)) % MOD; }}long m_long = m;long n_long = n;long sumX = (n_long * n_long % MOD * sum_diff_m) % MOD; // Calculate SumYlong sum_diff_n = 0;for (long i = 0; i < n; i++) { for (long j = i + 1; j < n; j++) { sum_diff_n = (sum_diff_n + (j - i)) % MOD; }}long sumY = (m_long * m_long % MOD * sum_diff_n) % MOD; long totalDist = (sumX + sumY) % MOD; // Calculate combinations and final answer as in other approacheslong combinations = nCr_mod_p(N - 2, k - 2, fact, invFact, MOD);long ans = (totalDist * combinations) % MOD;Complexity
Time
O(m*n + m^2 + n^2). This is faster than `O((m*n)^2)` but fails if either `m` or `n` is large (e.g., `m=10^5, n=1`).
Space
O(m*n) for precomputed factorials.
Trade-offs
Pros
More efficient than the naive brute-force approach.
Introduces the idea of separating x and y distance calculations.
Cons
The complexity
O(m^2 + n^2)is still too slow for the given constraints, wheremorncan be up to10^5.
This approach provides a highly efficient solution by using a combinatorial formula to calculate the sum of distances between all cell pairs in constant time (after precomputation). The key insight is that the sum of differences between all pairs of indices from 0 to d-1, i.e., Sum_{0 <= i < j < d} (j-i), can be expressed by the closed-form formula (d^3 - d) / 6. By applying this formula to both rows and columns, we can calculate the total sum of distances efficiently.
Algorithm
- The total sum is
C(N-2, k-2) * (SumX + SumY), whereN = m*n. - Recognize that the sum
S_d = Sum_{0 <= i < j < d} (j-i)has a closed-form formula:S_d = (d^3 - d) / 6. - Calculate
SumX = n^2 * S_m = n^2 * (m^3 - m) / 6. - Calculate
SumY = m^2 * S_n = m^2 * (n^3 - n) / 6. - All calculations must be performed using modular arithmetic. Division by 6 is done by multiplying with the modular multiplicative inverse of 6.
- The term
d^3 - d = d(d-1)(d+1)is a product of three consecutive integers, so it is always divisible by 6, ensuring the division is valid over integers. - Precompute factorials up to
Nto findC(N-2, k-2)inO(1)time. - Combine the terms to get the final answer.
Walkthrough
This method is based on the same reframing as the previous approaches but uses a mathematical formula for an efficient calculation.
-
The Formula The total sum is
TotalSum = C(N-2, k-2) * (SumX + SumY) % MOD.SumX = n^2 * (Sum_{0 <= i < j < m} (j-i))SumY = m^2 * (Sum_{0 <= i < j < n} (j-i)) -
Closed-Form for Sum of Differences The sum
Sum_{0 <= i < j < d} (j-i)can be proven to be equal to(d^3 - d) / 6. Therefore, we can calculateSumXandSumYinO(1)time (with large number arithmetic).SumX = n^2 * (m^3 - m) / 6SumY = m^2 * (n^3 - n) / 6 -
Modular Arithmetic Since we need the result modulo
10^9 + 7, all calculations must be done modulo this prime. Division by 6 is handled by multiplying by the modular inverse of 6, which can be calculated using Fermat's Little Theorem:6^(MOD-2) % MOD. -
Implementation The overall algorithm involves precomputing factorials up to
N = m*n, calculating the modular inverse of 6, and then plugging the values ofmandninto the formulas forSumXandSumY.
Here is a complete Java implementation:
class Solution { private static final int MOD = 1_000_000_007; private long[] fact; private long[] invFact; public int sumOfManhattanDistances(int m, int n, int k) { if (k < 2) { return 0; } long N = (long) m * n; precomputeFactorials((int)N); long combinations = nCr_mod_p(N - 2, k - 2); long m_long = m; long n_long = n; long inv6 = power(6, MOD - 2); // Calculate sum of differences for rows: (m^3 - m) / 6 long term_m = (m_long * (m_long - 1)) % MOD; term_m = (term_m * (m_long + 1)) % MOD; term_m = (term_m * inv6) % MOD; // Calculate sum of differences for columns: (n^3 - n) / 6 long term_n = (n_long * (n_long - 1)) % MOD; term_n = (term_n * (n_long + 1)) % MOD; term_n = (term_n * inv6) % MOD; // SumX = n^2 * term_m long sumX = (n_long * n_long % MOD * term_m) % MOD; // SumY = m^2 * term_n long sumY = (m_long * m_long % MOD * term_n) % MOD; long totalDist = (sumX + sumY) % MOD; long ans = (combinations * totalDist) % MOD; return (int) ans; } private void precomputeFactorials(int maxN) { fact = new long[maxN + 1]; invFact = new long[maxN + 1]; fact[0] = 1; invFact[0] = 1; for (int i = 1; i <= maxN; i++) { fact[i] = (fact[i - 1] * i) % MOD; invFact[i] = power(fact[i], MOD - 2); } } private long power(long base, long exp) { long res = 1; base %= MOD; while (exp > 0) { if (exp % 2 == 1) res = (res * base) % MOD; base = (base * base) % MOD; exp /= 2; } return res; } private long nCr_mod_p(long n, long r) { if (r < 0 || r > n) { return 0; } return (((fact[(int)n] * invFact[(int)r]) % MOD) * invFact[(int)(n - r)]) % MOD; }}Complexity
Time
O(m*n) dominated by the precomputation of factorials. The main calculation is O(log MOD) for the modular inverse.
Space
O(m*n) for storing precomputed factorials and their inverses.
Trade-offs
Pros
Highly efficient with a time complexity linear in
m*n.Solves the problem well within the given constraints.
Demonstrates a powerful problem-solving technique combining combinatorics and modular arithmetic.
Cons
Requires knowledge of combinatorial identities and modular arithmetic, including modular inverse.
The derivation of the formula is not immediately obvious.
Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.