You are given a 2D grid of strings grid
, where each string is a sequence of digits. This grid represents a table of numerical values. You need to find the width of each column, where the width of a column is defined as the maximum length of the string in that column. The result should be returned as a list of integers, representing the widths of the columns from left to right.
Constraints:
grid
is a list of lists.Here’s the Python code to solve the problem:
def findColumnWidths(grid):
if not grid or not grid[0]:
return []
num_rows = len(grid)
num_cols = len(grid[0])
column_widths = [0] * num_cols
for col in range(num_cols):
max_width = 0
for row in range(num_rows):
max_width = max(max_width, len(grid[row][col]))
column_widths[col] = max_width
return column_widths
# Example Usage
grid = [
["123", "4", "56"],
["78", "91011", "12"],
["3456", "7", "89"]
]
print(findColumnWidths(grid)) # Output: [4, 5, 3]
This solution ensures that we efficiently calculate the maximum column width by checking each element in the grid only once, making it optimal for the problem’s constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?