LeetCode Solutions

296. Best Meeting Point

Time: $O(mn)$

Space: $O(mn)$

			

class Solution {
 public:
  int minTotalDistance(vector<vector<int>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    vector<int> I;  // I indices s.t. grid[i][j] == 1
    vector<int> J;  // J indices s.t. grid[i][j] == 1

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (grid[i][j])
          I.push_back(i);

    for (int j = 0; j < n; ++j)
      for (int i = 0; i < m; ++i)
        if (grid[i][j])
          J.push_back(j);

    // Sum(i - median(I)) + sum(j - median(J))
    return minTotalDistance(I) + minTotalDistance(J);
  }

 private:
  int minTotalDistance(const vector<int>& grid) {
    int sum = 0;
    int i = 0;
    int j = grid.size() - 1;

    while (i < j)
      sum += grid[j--] - grid[i++];

    return sum;
  }
};
			

class Solution {
  public int minTotalDistance(int[][] grid) {
    final int m = grid.length;
    final int n = grid[0].length;
    List<Integer> I = new ArrayList<>(); // I indices s.t. grid[i][j] == 1
    List<Integer> J = new ArrayList<>(); // J indices s.t. grid[i][j] == 1

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (grid[i][j] == 1)
          I.add(i);

    for (int j = 0; j < n; ++j)
      for (int i = 0; i < m; ++i)
        if (grid[i][j] == 1)
          J.add(j);

    // Sum(i - median(I)) + sum(j - median(J))
    return minTotalDistance(I) + minTotalDistance(J);
  }

  private int minTotalDistance(List<Integer> grid) {
    int sum = 0;
    int i = 0;
    int j = grid.size() - 1;

    while (i < j)
      sum += grid.get(j--) - grid.get(i++);

    return sum;
  }
}
			

class Solution:
  def minTotalDistance(self, grid: List[List[int]]) -> int:
    m = len(grid)
    n = len(grid[0])
    # I indices s.t. grid[i][j] == 1
    I = [i for i in range(m) for j in range(n) if grid[i][j]]
    # J indices s.t. grid[i][j] == 1
    J = [j for j in range(n) for i in range(m) if grid[i][j]]

    def minTotalDistance(grid: List[int]) -> int:
      summ = 0
      i = 0
      j = len(grid) - 1

      while i < j:
        summ += grid[j] - grid[i]
        i += 1
        j -= 1

      return summ

    # Sum(i - median(I)) + sum(j - median(J))
    return minTotalDistance(I) + minTotalDistance(J)