Minimize Maximum Value in a Grid - Problem

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:

1. The relative order of every two elements that are in the same row or column should stay the same after the replacements.

2. The maximum number in the matrix after the replacements should be as small as possible.

The relative order stays the same if for all pairs of elements in the original matrix such that grid[r1][c1] > grid[r2][c2] where either r1 == r2 or c1 == c2, then it must be true that grid[r1][c1] > grid[r2][c2] after the replacements.

For example, if grid = [[2, 4, 5], [7, 3, 9]] then a good replacement could be either grid = [[1, 2, 3], [2, 1, 4]] or grid = [[1, 2, 3], [3, 1, 4]].

Return the resulting matrix. If there are multiple answers, return any of them.

Input & Output

Example 1 — Basic Grid
$ Input: grid = [[2,4,5],[7,3,9]]
Output: [[1,2,3],[2,1,4]]
💡 Note: Process elements by value: 2→rank 1, 3→rank 1, 4→rank 2, 5→rank 3, 7→rank 2, 9→rank 4. Each rank respects row/column ordering constraints.
Example 2 — Single Row
$ Input: grid = [[1,3,2]]
Output: [[1,3,2]]
💡 Note: In a single row, elements must maintain their relative order: 1 < 2 < 3, so the minimum assignment is [1,3,2].
Example 3 — Single Column
$ Input: grid = [[5],[2],[8]]
Output: [[2],[1],[3]]
💡 Note: In a single column, we process 2→1, 5→2, 8→3 to maintain the constraint 2 < 5 < 8.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 1000
  • 1 ≤ grid[i][j] ≤ 109
  • All integers in grid are distinct

Visualization

Tap to expand
Minimize Maximum Value in GridInput:245739Output:123214Constraints:• Row order: 2 < 4 < 5 and 7 > 3 < 9• Column order: 2 < 7, 4 > 3, 5 < 9• Minimize maximum value in result✓ All constraints satisfied• Row order: 1 < 2 < 3 and 2 > 1 < 4• Column order: 1 < 2, 2 > 1, 3 < 4• Maximum value = 4 (minimized)Algorithm: Process elements by value, assign minimum valid rank
Understanding the Visualization
1
Input Grid
Original grid with distinct positive integers
2
Maintain Order
Preserve relative order within each row and column
3
Minimize Maximum
Assign smallest possible values while respecting constraints
Key Takeaway
🎯 Key Insight: Process elements in ascending order and assign each the minimum rank that respects existing row/column maximums
Asked in
Google 15 Amazon 8 Microsoft 6
15.6K Views
Medium Frequency
~35 min Avg. Time
425 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen