Find the Width of Columns of a Grid

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def findColumnWidth(self, grid: List[List[int]]) -> List[int]:
        m, n = len(grid), len(grid[0])
        widths = [0] * n

        # Iterate Through Columns
        for j in range(n):
            max_length = 0

            # Calculate Length
            for i in range(m):
                length = len(str(abs(grid[i][j])))  # Take absolute value
                if grid[i][j] < 0:
                    length += 1  # Add 1 for negative sign
                max_length = max(max_length, length)

            # Store Width
            widths[j] = max_length

        # Return Result
        return widths

Explanation

  • This code finds the absolute value of each integer to calculate its length and adds 1 if the integer is negative.
  • This gives the correct widths of the columns, such as [3, 1, 2] for grid = [[-15,1,3],[15,7,12],[5,6,-2]].