#3426

Manhattan Distances of All Arrangements of Pieces

Hard
MathCombinatoricsCombinatorial CountingMathematical Optimization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n * m * n)
Space
O(1)
O(1)
💡

Intuition

Time O(m * n * m * n)Space O(1)

Instead of calculating distances for every arrangement, we can fix pairs of pieces and calculate how many arrangements can be formed with them fixed. This reduces the number of calculations significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Iterate through all pairs of positions on the grid.
  2. 2Step 2: For each pair, calculate the Manhattan distance.
  3. 3Step 3: Count how many valid arrangements can be formed with the remaining k-2 pieces using combinations.
  4. 4Step 4: Multiply the distance by the number of arrangements and sum it up.
solution.py16 lines
1# Full working Python code
2from math import comb
3
4MOD = 10**9 + 7
5def manhattan_distance_optimal(m, n, k):
6    total_distance = 0
7    for x1 in range(m):
8        for y1 in range(n):
9            for x2 in range(m):
10                for y2 in range(n):
11                    if (x1, y1) != (x2, y2):
12                        distance = abs(x1 - x2) + abs(y1 - y2)
13                        arrangements = comb(m * n - 2, k - 2)
14                        total_distance += distance * arrangements
15                        total_distance %= MOD
16    return total_distance

Complexity note: The complexity is due to iterating through all pairs of positions on the grid, which is manageable given the constraints.

  • 1Fixing pairs of positions allows us to count arrangements efficiently.
  • 2The Manhattan distance can be calculated directly from the coordinates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.