Minimize total distance to a store
Problem: Minimize Total Distance to a Store
You are given an M x N grid grid containing only 0s and 1s.
grid[r][c] = 1signifies a demand point at cell(r, c)(e.g., a customer's home).grid[r][c] = 0signifies no demand at that cell.
Your task is to place exactly one store at any cell (r, c) within the grid. This includes cells that might already have a demand point (1). The objective is to choose the store location that minimizes the total distance from every demand cell (1) to the chosen store.
The distance metric to be used is Manhattan distance, defined as d((r1,c1),(r2,c2)) = |r1 - r2| + |c1 - c2|.
Input
grid: AnM x Nmatrix composed of0s and1s.
Output
- Return the minimum possible total distance.
Notes
- If there are no demand points (
1s) in the grid, the minimum total distance is0. - Be prepared to discuss both a brute-force approach and an optimal approach to solve this problem.
AI interview prep
Core dilemma
Efficiently finding the optimal meeting point (L1 median) for a set of scattered points in a 2D grid, leveraging the separability property of Manhattan distance to reduce complexity.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Minimize total distance to a store
Problem: Minimize Total Distance to a Store
You are given an M x N grid grid containing only 0s and 1s.
grid[r][c] = 1signifies a demand point at cell(r, c)(e.g., a customer's home).grid[r][c] = 0signifies no demand at that cell.
Your task is to place exactly one store at any cell (r, c) within the grid. This includes cells that might already have a demand point (1). The objective is to choose the store location that minimizes the total distance from every demand cell (1) to the chosen store.
The distance metric to be used is Manhattan distance, defined as d((r1,c1),(r2,c2)) = |r1 - r2| + |c1 - c2|.
Input
grid: AnM x Nmatrix composed of0s and1s.
Output
- Return the minimum possible total distance.
Notes
- If there are no demand points (
1s) in the grid, the minimum total distance is0. - Be prepared to discuss both a brute-force approach and an optimal approach to solve this problem.