Minimize Grid Inconvenience by Adding One Delivery Center
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Overview: Add at most one delivery center to minimize the maximum Chebyshev distance from ordinary grid cells to their nearest center.
Constraints
- 1 <= number of rows <= 500.
- 1 <= number of columns <= 500.
- grid is a rectangular integer matrix: every row has the same number of columns.
- Every entry is 0 or 1.
- At most one 0 cell may be converted into a delivery center; existing delivery centers remain in place.
- Distances use the Chebyshev formula max(abs(r1 - r2), abs(c1 - c2)); distances depend only on coordinates, and there are no obstacles or path restrictions.
- The grid may initially contain no delivery center. In that case, placing one center is allowed and makes the final distances well defined.
- As an explicit edge-case convention, a final grid with no ordinary locations has inconvenience 0.
- Adding no center is permitted when the existing arrangement is already optimal.
- The returned value is an integer between 0 and 499 inclusive, so it fits comfortably in a 32-bit signed integer.
Examples
Input: ([[0]],)
Expected Output: 0
Explanation: Minimum valid grid with no center: converting the only cell leaves no ordinary location, so the inconvenience is 0.
Input: ([[1]],)
Expected Output: 0
Explanation: A 1x1 grid that is already a center has no ordinary location, so the inconvenience is 0.
Hints
- Under the stated distance formula, the set of cells within distance d of a fixed cell is an axis-aligned square, not a diamond.
- Focus on locations that the existing centers do not cover: for a proposed maximum distance, only some ordinary locations still need help.
- Rather than deciding where the new center should go, first ask whether a proposed maximum distance is achievable at all, and determine whether one grid position could cover every still-uncovered location under the stated distance formula.