Find the Width of Columns of a Grid - Problem
You are given a 0-indexed m x n integer matrix grid. The width of a column is the maximum length of its integers.
For example, if grid = [[-10], [3], [12]], the width of the only column is 3 since -10 is of length 3.
Return an integer array ans of size n where ans[i] is the width of the ith column.
The length of an integer x with len digits is equal to len if x is non-negative, and len + 1 otherwise.
Input & Output
Example 1 — Basic Case
$
Input:
grid = [[1,2,3],[-10,-20,100],[4,5,6]]
›
Output:
[3,3,3]
💡 Note:
Column 0: max(len('1'), len('-10'), len('4')) = max(1, 3, 1) = 3. Column 1: max(len('2'), len('-20'), len('5')) = max(1, 3, 1) = 3. Column 2: max(len('3'), len('100'), len('6')) = max(1, 3, 1) = 3.
Example 2 — Single Column
$
Input:
grid = [[-10],[3],[12]]
›
Output:
[3]
💡 Note:
Only one column with values -10 (length 3), 3 (length 1), and 12 (length 2). Maximum is 3.
Example 3 — Mixed Values
$
Input:
grid = [[7],[-7]]
›
Output:
[2]
💡 Note:
Column has 7 (length 1) and -7 (length 2 due to minus sign). Maximum width is 2.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 100
- -109 ≤ grid[i][j] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
2D grid with integers, including negatives
2
Calculate Widths
For each number, count digits plus sign if negative
3
Find Column Max
Return maximum width per column as array
Key Takeaway
🎯 Key Insight: Negative numbers need an extra character for the minus sign, affecting the total width calculation.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code