Manhattan Distances of All Arrangements of Pieces - Problem

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|.

Input & Output

Example 1 — Small Grid
$ Input: m = 1, n = 2, k = 2
Output: 1
💡 Note: Only one arrangement possible: both pieces at positions (0,0) and (0,1). Distance = |0-0| + |0-1| = 1.
Example 2 — Square Grid
$ Input: m = 2, n = 2, k = 2
Output: 8
💡 Note: Grid has 4 cells, C(4,2) = 6 arrangements. Sum of all pairwise distances across arrangements equals 8.
Example 3 — Single Piece
$ Input: m = 3, n = 3, k = 1
Output: 0
💡 Note: With only one piece, there are no pairs to calculate distance between, so sum is 0.

Constraints

  • 1 ≤ m, n ≤ 100
  • 1 ≤ k ≤ m × n
  • Answer fits in 32-bit integer after modulo

Visualization

Tap to expand
Manhattan Distances of All Arrangements INPUT 1x2 Grid with 2 pieces P1 P2 (0,0) (0,1) Distance = 1 m = 1 rows n = 2 cols k = 2 pieces Total cells: m × n = 2 Only 1 arrangement C(2,2) = 1 way MOD = 10^9 + 7 ALGORITHM STEPS 1 Count Pairs C(k,2) = k*(k-1)/2 = 2*1/2 = 1 pair 2 Sum X-distances |x1-x2| for all pairs |0-0| = 0 3 Sum Y-distances |y1-y2| for all pairs |0-1| = 1 4 Combine Results Total = SumX + SumY = 0 + 1 = 1 Calculation Summary Arrangements: C(2,2) = 1 Manhattan dist: |0-0|+|0-1|=1 FINAL RESULT All Valid Arrangements: Arrangement #1 Distance in this arrangement: |0-0| + |0-1| = 1 OUTPUT 1 [OK] Sum of all distances mod 10^9+7 = 1 Total arrangements: 1 Key Insight: The optimal approach separates X and Y coordinates. For each dimension, count contribution of each distance independently. Multiply by number of arrangements with remaining k-2 pieces. Formula: Sum all |xi-xj| * C(m*n-2, k-2) for each pair, then combine X and Y contributions. TutorialsPoint - Manhattan Distances of All Arrangements of Pieces | Optimal Solution
Asked in
Google 25 Meta 18 Microsoft 15 Amazon 12
12.4K Views
Medium Frequency
~35 min Avg. Time
285 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen