Find the Width of Columns of a Grid - Problem
Imagine you're designing a data visualization tool that needs to calculate the display width of columns in a spreadsheet-like grid. Each column contains integers of varying lengths, and you need to determine how much horizontal space each column requires.
Given a m × n integer matrix grid, your task is to find the width of each column, where the width is defined as the maximum character length needed to display any number in that column.
Important: Negative numbers require an extra character for the minus sign!
Example: If a column contains [-10, 3, 12], the widths are:
-10→ 3 characters (including minus sign)3→ 1 character12→ 2 characters
So this column has width 3.
Return an integer array where ans[i] represents the width of the i-th column.
Input & Output
example_1.py — Basic Example
$
Input:
grid = [[1,2,3],[11,12,13]]
›
Output:
[2, 2, 2]
💡 Note:
Column 0: max(len('1'), len('11')) = max(1, 2) = 2. Column 1: max(len('2'), len('12')) = max(1, 2) = 2. Column 2: max(len('3'), len('13')) = max(1, 2) = 2.
example_2.py — Negative Numbers
$
Input:
grid = [[-15,1,3],[15,-7,12]]
›
Output:
[3, 2, 2]
💡 Note:
Column 0: max(len('-15'), len('15')) = max(3, 2) = 3 (negative sign counts). Column 1: max(len('1'), len('-7')) = max(1, 2) = 2. Column 2: max(len('3'), len('12')) = max(1, 2) = 2.
example_3.py — Single Column
$
Input:
grid = [[-10],[3],[12]]
›
Output:
[3]
💡 Note:
Only one column with values -10 (3 chars), 3 (1 char), 12 (2 chars). Maximum width is 3.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 100
- -109 ≤ grid[i][j] ≤ 109
- The length of integer x with len digits is len if x ≥ 0, and len + 1 if x < 0
Visualization
Tap to expand
Understanding the Visualization
1
Scan Column
Go through each number in the column
2
Calculate Width
Count digits, add 1 for negative sign
3
Track Maximum
Keep the largest width found
4
Store Result
Save the column width to result array
Key Takeaway
🎯 Key Insight: We only need one pass through each column to find the maximum character width, making this an efficient O(m×n) solution for matrix traversal.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code