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
Find the Width of Columns of a Grid INPUT m x n integer matrix grid 1 2 3 -10 -20 100 4 5 6 Col 0 Col 1 Col 2 String Lengths: "1" = 1, "-10" = 3 "2" = 1, "-20" = 3 "3" = 1, "100" = 3 [[1,2,3],[-10,-20,100],[4,5,6]] ALGORITHM STEPS 1 Initialize Result ans = [0, 0, 0] 2 Traverse Row-by-Row For each cell in grid 3 Calculate Length len = str(num).length 4 Update Maximum ans[col] = max(ans[col], len) Processing Table Col 0 Col 1 Col 2 1-->1 2-->1 3-->1 -10-->3 -20-->3 100-->3 4-->1 5-->1 6-->1 max=3 max=3 max=3 FINAL RESULT Column Width Array 3 Col 0 3 Col 1 3 Col 2 [3, 3, 3] Width Explanation: Col 0: max(1,3,1) = 3 ("-10") Col 1: max(1,3,1) = 3 ("-20") Col 2: max(1,3,1) = 3 ("100") OK - Complete Key Insight: Convert each integer to string and count characters. Negative numbers include the '-' sign in length. Track maximum length per column using row-by-row traversal. Time: O(m*n), Space: O(n) for result array. TutorialsPoint - Find the Width of Columns of a Grid | Row-by-Row Traversal Approach
Asked in
Google 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen