Manhattan Distances of All Arrangements of Pieces Problem
Description
LeetCode Problem 3426.
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 10^9 + 7.
The Manhattan Distance between two cells (x_i, y_i) and (x_j, y_j) is |x_i - x_j| + |y_i - y_j|.
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 <= 10^52 <= m * n <= 10^52 <= k <= m * n
Solution
Approach: Counting Pairs of Cells
By linearity, the answer is the sum of the distance between two cells, over all pairs of cells, times the number of arrangements that contain both cells: C(m * n - 2, k - 2), the ways to place the other k - 2 pieces.
The distance splits into rows and columns. Two cells whose rows differ by d can be chosen in (m - d) ways for the pair of rows and n * n ways for the columns, so the rows contribute sum over d of d * (m - d) * n * n. The columns contribute sum over d of d * (n - d) * m * m in the same way. Multiply the total by the binomial coefficient, which we get from factorials and a modular inverse.
Complexity: O(m + n + m * n) time and O(m * n) space.
class Solution:
def distanceSum(self, m: int, n: int, k: int) -> int:
mod = 10**9 + 7
# Sum of distances over all pairs of cells: a pair of rows d apart occurs (m - d) * n * n times
# (the same for columns). Every pair of cells is used by C(m*n - 2, k - 2) arrangements.
pairs = 0
for d in range(1, m):
pairs += d * (m - d) * n * n
for d in range(1, n):
pairs += d * (n - d) * m * m
total = m * n - 2
fact = [1] * (total + 1)
for i in range(1, total + 1):
fact[i] = fact[i - 1] * i % mod
ways = fact[total] * pow(fact[k - 2] * fact[total - k + 2] % mod, mod - 2, mod) % mod
return pairs % mod * ways % mod