{x}
blog image

Minimize Maximum Value in a Grid

Solution Explanation

This problem asks to find a replacement for the values in a matrix such that the relative order of elements within rows and columns is preserved, and the maximum value in the resulting matrix is minimized. The solution leverages sorting and a greedy approach.

Approach:

  1. Sorting: We first flatten the matrix and sort the elements along with their original row and column indices. This allows us to process elements in increasing order of their original values.

  2. Greedy Replacement: We iterate through the sorted elements. For each element, we assign it the smallest possible value that maintains the relative order within its row and column. This value is one greater than the maximum of the largest values already assigned in its row and column.

  3. Row and Column Tracking: We use rowMax and colMax arrays to track the maximum values assigned in each row and column, respectively. When assigning a value to an element, we ensure it's larger than the current maximum in its row and column.

Time Complexity Analysis:

  • Sorting the elements takes O(N log N) time, where N is the number of elements in the matrix (m * n).
  • Iterating through the sorted elements and updating the rowMax and colMax arrays takes O(N) time.

Therefore, the overall time complexity is dominated by the sorting step, making it O(N log N).

Space Complexity Analysis:

  • We use rowMax and colMax arrays, each of size m and n respectively, to store the maximum values seen in each row and column. This takes O(m + n) space.
  • The sorted list nums requires O(N) space in the worst case.
  • The resulting matrix ans requires O(N) space.

The overall space complexity is therefore O(m + n + N) = O(N), which is linear to the number of elements in the matrix.

Code Explanation (Python):

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()  # Sort by original value
        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 #Assign smallest value maintaining order
            row_max[i] = col_max[j] = ans[i][j] #Update row and column max values
        return ans

The Python code directly implements the described algorithm. The other languages (Java, C++, Go, TypeScript) follow a very similar structure, adapting the syntax to their respective features. The core logic remains the same across all implementations.