We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Width of Columns of a Grid

Number: 2675

Difficulty: Easy

Paid? No

Companies: Samsung


Problem Description

Given an m x n integer matrix grid, compute the width of each column. The width of a column is defined as the maximum length of its integers, where the length of an integer is the number of digits it has if non-negative, and one extra to account for the '-' sign if it is negative.


Key Insights

  • You need to calculate the number of characters when an integer is converted to string.
  • A negative number will have an extra character (the '-' sign) compared to its absolute value.
  • Iterate column by column and compute the maximum length for each column.
  • The problem has modest constraints allowing a simple nested loop solution.

Space and Time Complexity

Time Complexity: O(m * n) where m is the number of rows and n is the number of columns. Space Complexity: O(n) for storing the result array.


Solution

We iterate over each column and for each column, iterate over every row to check the string length of the integer at that position. For each integer, convert it to a string to compute its length (this inherently handles negative numbers by including the '-' sign) and update the maximum length for that column. Finally, we store the maximum lengths in a result array which is returned as the answer.


Code Solutions

# Function to compute the column widths of a grid
def findColumnWidth(grid):
    # Number of rows and columns
    m = len(grid)
    n = len(grid[0])
    # Initialize the result array with zeros for each column
    result = [0] * n
    # Loop through each column
    for col in range(n):
        # For each column, compute the width by checking every row
        for row in range(m):
            # Convert the integer to string to account for the '-' sign
            num_str = str(grid[row][col])
            # Update the maximum length for the current column
            result[col] = max(result[col], len(num_str))
    return result

# Example usage:
grid1 = [[1], [22], [333]]
print(findColumnWidth(grid1))  # Output: [3]

grid2 = [[-15, 1, 3], [15, 7, 12], [5, 6, -2]]
print(findColumnWidth(grid2))  # Output: [3, 1, 2]
← Back to All Questions