Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2371: Minimize Maximum Value in a Grid

In this guide, we solve Leetcode #2371 Minimize Maximum Value in a Grid in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an m x n integer matrix grid containing distinct positive integers. You have to replace each integer in the matrix with a positive integer satisfying the following conditions: The relative order of every two elements that are in the same row or column should stay the same after the replacements.

Quick Facts

  • Difficulty: Hard
  • Premium: Yes
  • Tags: Union Find, Graph, Topological Sort, Array, Matrix, Sorting

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

Example

Input: grid = [[3,1],[2,5]] Output: [[2,1],[1,2]] Explanation: The above diagram shows a valid replacement. The maximum number in the matrix is 2. It can be shown that no smaller value can be obtained.

Python Solution

class Solution: def minScore(self, grid: List[List[int]]) -> List[List[int]]: m, n = len(grid), len(grid[0]) nums = [(v, i, j) for i, row in enumerate(grid) for j, v in enumerate(row)] nums.sort() row_max = [0] * m col_max = [0] * n ans = [[0] * n for _ in range(m)] for _, i, j in nums: ans[i][j] = max(row_max[i], col_max[j]) + 1 row_max[i] = col_max[j] = ans[i][j] return ans

Complexity

The time complexity is O(V+E). The space complexity is O(V).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy