Find the Width of Columns of a Grid solution and explanation
9 more videos on this problem
6333. Find the Width of Columns of a Grid | Leetcode Biweekly Contest 102 | Solution | JAVA.Optimization · 2:49 · 405 views
Leetcode 2639: Find the Width of Columns of a GridAlgorithms Casts · 5:02 · 377 views
Find the Width of Columns of a Grid || leetcode Biweekly 102 || Leetcode EasyBinaryMagic · 5:05 · 287 views
2639. Find the Width of Columns of a Grid (Leetcode Easy)Programming Live with Larry · 4:24 · 171 views
Leetcode BiWeekly contest 102 - Easy - Find the Width of Columns of a GridPrakhar Agrawal · 2:37 · 123 views
Leetcode biweekly contest 102 c++ solution summary (Problem 2642, 2641, 2640, 2639)猹妈的卷题日记_ChaMaCo · 14:29 · 98 views
Biweekly Contest 102 | 6333. Find the Width of Columns of a Grid | LeetCode | JAVANiharika Mishra · 0:29 · 96 views
6333. Find the Width of Columns of a Grid || Biweekly Contest 102 || Leetcode Solutions #subscribeCodeCake · 1:01 · 66 views
Find the Width of Columns of a Grid #LeetCode #java #coding #intervewQuestions #dsa #microsoftCodeVia · 3:10 · 48 views
Day 586 - Teaching Kids Programming - Find the Width of Columns of a Grid (Zip, Matrix Transpose)Doctor Lai · 16:43 · 40 views
The 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 is3since-10is of length3.
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.
Example 1:
Input: grid = [[1],[22],[333]] Output: [3] Explanation: In the 0th column, 333 is of length 3.
Example 2:
Input: grid = [[-15,1,3],[15,7,12],[5,6,-2]] Output: [3,1,2] Explanation: In the 0th column, only -15 is of length 3. In the 1st column, all integers are of length 1. In the 2nd column, both 12 and -2 are of length 2.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 100-109 <= grid[r][c] <= 109
Approach overview
Problem Overview: You are given an m x n integer grid. For each column, compute the display width required to print all values in that column. The width equals the maximum number of characters needed to represent any number in that column (including the minus sign for negative numbers).
Approach 1: Simple Iteration Over Columns (Time: O(m*n), Space: O(n))
The direct approach scans the grid column by column. For each column j, iterate through every row i and convert grid[i][j] into a string using str() or its equivalent. Track the maximum string length seen in that column. Store the result in an output array where ans[j] represents the width of column j. The key observation is that the width of a column depends only on the longest formatted number in that column.
This approach relies on straightforward iteration over the matrix. Each element is visited exactly once, and the cost of computing the string length is constant for typical integer ranges. The solution is simple, readable, and works well for interview settings where clarity matters.
Approach 2: Optimized Column-Wise Pass (Time: O(m*n), Space: O(n))
The optimized variation avoids repeated string allocations. Instead of converting numbers to strings, compute the number of digits mathematically. For each value, take the absolute value and count digits using division or log10. If the number is negative, add one extra character for the minus sign. Compare this computed length with the current maximum width for the column.
This method still performs a single pass across the grid but reduces temporary string creation. When working with very large grids or performance-sensitive environments, avoiding string conversion can slightly reduce overhead. The logic remains column-oriented and uses only a result array to track widths.
The algorithm naturally fits problems involving arrays and matrix traversal. You iterate through columns, compute a property of each element, and keep a running maximum.
Recommended for interviews: The simple iteration approach is usually expected. It clearly shows that you understand column traversal and how formatted length determines width. Mentioning the mathematical digit-count optimization demonstrates deeper awareness of performance tradeoffs, but both approaches have the same asymptotic complexity of O(m*n) time and O(n) extra space.
Approach 1: Simple Iteration Over Columns
To solve this problem, iterate over each column and calculate the maximum length of integers in that column. We can achieve this by checking each column element one at a time, converting it to its string representation to determine its length. Iterate through all columns to find the widths.
def findColumnWidths(grid):
m = len(grid)
n = len(grid[0])
widths = [0] * n
for j in range(n):
maxLength = 0
for i in range(m):
length = len(str(grid[i][j]))
maxLength = max(maxLength, length)
widths[j] = maxLength
return widths
# Example Usage
if __name__ == "__main__":
grid = [[1], [22], [333]]
print(findColumnWidths(grid))import java.util.*;
public class Main {
public static int[] findColumnWidths(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[] widths = new int[n];
for (int j = 0; j < n; j++) {
int maxLength = 0;
for (int i = 0; i < m; i++) {
int length = String.valueOf(grid[i][j]).length();
maxLength = Math.max(maxLength, length);
}
widths[j] = maxLength;
}
return widths;
}
public static void main(String[] args) {
int[][] grid = {{1}, {22}, {333}};
int[] result = findColumnWidths(grid);
for (int width : result) {
System.out.print(width + " ");
}
}
}#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<int> findColumnWidths(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<int> widths(n);
for (int j = 0; j < n; j++) {
int maxLength = 0;
for (int i = 0; i < m; i++) {
int length = to_string(grid[i][j]).length();
maxLength = max(maxLength, length);
}
widths[j] = maxLength;
}
return widths;
}
int main() {
vector<vector<int>> grid = {{1}, {22}, {333}};
vector<int> result = findColumnWidths(grid);
for (int width : result) {
cout << width << " ";
}
return 0;
}function findColumnWidths(grid) {
let m = grid.length;
let n = grid[0].length;
let widths = Array(n).fill(0);
for (let j = 0; j < n; j++) {
let maxLength = 0;
for (let i = 0; i < m; i++) {
let length = grid[i][j].toString().length;
maxLength = Math.max(maxLength, length);
}
widths[j] = maxLength;
}
return widths;
}
// Example usage
let grid = [[1], [22], [333]];
console.log(findColumnWidths(grid));#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *findColumnWidths(int** grid, int gridSize, int* gridColSize, int* returnSize) {
*returnSize = gridColSize[0];
int* widths = (int*)malloc(sizeof(int) * (*returnSize));
for (int j = 0; j < *returnSize; j++) {
widths[j] = 0;
for (int i = 0; i < gridSize; i++) {
int num = grid[i][j];
int length = snprintf(NULL, 0, "%d", num);
if (length > widths[j]) {
widths[j] = length;
}
}
}
return widths;
}
int main() {
int gridSize = 3;
int gridColSize[] = {1, 1, 1};
int* grid[] = {(int[]){1}, (int[]){22}, (int[]){333}};
int returnSize;
int* result = findColumnWidths(grid, gridSize, gridColSize, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", result[i]);
}
free(result);
return 0;
}using System;
class Program {
public static int[] FindColumnWidths(int[][] grid) {
int m = grid.Length;
int n = grid[0].Length;
int[] widths = new int[n];
for (int j = 0; j < n; j++) {
int maxLength = 0;
for (int i = 0; i < m; i++) {
int length = grid[i][j].ToString().Length;
maxLength = Math.Max(maxLength, length);
}
widths[j] = maxLength;
}
return widths;
}
static void Main() {
int[][] grid = new int[][] { new int[] { 1 }, new int[] { 22 }, new int[] { 333 } };
int[] result = FindColumnWidths(grid);
Console.WriteLine(string.Join(" ", result));
}
}For each column, this implementation in Python uses a nested loop to determine the maximum integer length of the elements in the column. `str()` is used to convert the integer to its string representation, and `len()` is then used to find its length.
Time Complexity: O(m * n) because every element in the grid is processed once.
Space Complexity: O(n) to store the column widths.
Approach 2: Optimized Column-Wise Pass
This approach limits excess computation by leveraging stored intermediate lengths for each integer. It maintains a running list of maximum lengths, updating it with each new integer's length if it exceeds the current maximum for that column.
def findColumnWidths(grid):
m, n = len(grid), len(grid[0])
widths = [0] * n
for i in range(m):
for j in range(n):
widths[j] = max(widths[j], len(str(grid[i][j])))
return widths
# Example Usage
if __name__ == "__main__":
grid = [[1], [22], [333]]
print(findColumnWidths(grid))import java.util.*;
public class Main {
public static int[] findColumnWidths(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[] widths = new int[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
widths[j] = Math.max(widths[j], String.valueOf(grid[i][j]).length());
}
}
return widths;
}
public static void main(String[] args) {
int[][] grid = {{1}, {22}, {333}};
int[] result = findColumnWidths(grid);
for (int width : result) {
System.out.print(width + " ");
}
}
}#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<int> findColumnWidths(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<int> widths(n);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
widths[j] = max(widths[j], int(to_string(grid[i][j]).length()));
}
}
return widths;
}
int main() {
vector<vector<int>> grid = {{1}, {22}, {333}};
vector<int> result = findColumnWidths(grid);
for (int width : result) {
cout << width << " ";
}
return 0;
}function findColumnWidths(grid) {
let m = grid.length, n = grid[0].length;
let widths = Array(n).fill(0);
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
widths[j] = Math.max(widths[j], grid[i][j].toString().length);
}
}
return widths;
}
// Example usage
let grid = [[1], [22], [333]];
console.log(findColumnWidths(grid));#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *findColumnWidths(int** grid, int gridSize, int* gridColSize, int* returnSize) {
*returnSize = gridColSize[0];
int* widths = (int*)calloc(*returnSize, sizeof(int));
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < *returnSize; j++) {
int num = grid[i][j];
int length = snprintf(NULL, 0, "%d", num);
if (length > widths[j]) {
widths[j] = length;
}
}
}
return widths;
}
int main() {
int gridSize = 3;
int gridColSize[] = {1, 1, 1};
int* grid[] = {(int[]){1}, (int[]){22}, (int[]){333}};
int returnSize;
int* result = findColumnWidths(grid, gridSize, gridColSize, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", result[i]);
}
free(result);
return 0;
}using System;
class Program {
public static int[] FindColumnWidths(int[][] grid) {
int m = grid.Length, n = grid[0].Length;
int[] widths = new int[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
widths[j] = Math.Max(widths[j], grid[i][j].ToString().Length);
}
}
return widths;
}
static void Main() {
int[][] grid = new int[][] { new int[] { 1 }, new int[] { 22 }, new int[] { 333 } };
int[] result = FindColumnWidths(grid);
Console.WriteLine(string.Join(" ", result));
}
}Employing concise state-tracking for the widths while traversing each grid cell, this Python method highlights sequential processing analogous to language-native list comprehensions in principle.
Time Complexity: O(m * n) in correlation with interpreting each matrix element once and plain O(n) memory for column length storage.
Approach 3: Simulation
We denote the number of columns in the matrix as n, and create an array ans of length n, where ans[i] represents the width of the i-th column. Initially, ans[i] = 0.
We traverse each row in the matrix. For each element in each row, we calculate its string length w, and update the value of ans[j] to be max(ans[j], w).
After traversing all rows, each element in the array ans is the width of the corresponding column.
The time complexity is O(m times n), and the space complexity is O(log M). Where m and n are the number of rows and columns in the matrix respectively, and M is the absolute value of the maximum element in the matrix.
function findColumnWidth(grid: number[][]): number[] {
const n = grid[0].length;
const ans: number[] = new Array(n).fill(0);
for (const row of grid) {
for (let j = 0; j < n; ++j) {
const w: number = String(row[j]).length;
ans[j] = Math.max(ans[j], w);
}
}
return ans;
}func findColumnWidth(grid [][]int) []int {
ans := make([]int, len(grid[0]))
for _, row := range grid {
for j, x := range row {
w := len(strconv.Itoa(x))
ans[j] = max(ans[j], w)
}
}
return ans
}impl Solution {
pub fn find_column_width(grid: Vec<Vec<i32>>) -> Vec<i32> {
let mut ans = vec![0; grid[0].len()];
for row in grid.iter() {
for (j, num) in row.iter().enumerate() {
let width = num.to_string().len() as i32;
ans[j] = std::cmp::max(ans[j], width);
}
}
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Simple Iteration Over Columns | Time Complexity: O(m * n) because every element in the grid is processed once. |
| Optimized Column-Wise Pass | Time Complexity: O(m * n) in correlation with interpreting each matrix element once and plain O(n) memory for column length storage. |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Simple Iteration Over Columns | O(m*n) | O(n) | Best general solution. Clean and easy to implement using string length. |
| Optimized Column-Wise Pass (Digit Counting) | O(m*n) | O(n) | When avoiding string conversions or optimizing numeric processing. |
Frequently asked questions
Is Find the Width of Columns of a Grid easy or hard?
Find the Width of Columns of a Grid is an easy-level problem. It focuses on basic matrix traversal, simple comparisons, and handling integer formatting edge cases such as negative numbers.
Find the Width of Columns of a Grid Python/Java solution
In Python or Java, iterate over each column and check every element in that column. Convert the integer to a string (or compute digit length) and track the maximum length. Store that maximum in the result array for the column.
How to solve Find the Width of Columns of a Grid in O(n)?
The full grid must be inspected, so the overall complexity is O(m*n). You achieve this by scanning column by column and updating the maximum character length for each column. Each element contributes a constant-time width calculation.
What is the best approach for Find the Width of Columns of a Grid?
The most practical approach is column-wise iteration. For each column, scan all rows and compute the length of each number’s string representation, keeping the maximum. This runs in O(m*n) time and uses O(n) space for the result array.
Is Find the Width of Columns of a Grid asked at Google/Amazon/Meta?
This problem is categorized as an easy matrix traversal question similar to those asked in screening rounds at companies like Amazon and Google. It tests basic array and matrix iteration along with attention to detail when formatting integers.
What data structure is used in Find the Width of Columns of a Grid?
The solution primarily uses arrays and a matrix. The input is a 2D grid, and the output is a one-dimensional array storing the maximum width for each column.
What is the time complexity of Find the Width of Columns of a Grid?
The time complexity is O(m*n), where m is the number of rows and n is the number of columns. Each grid element is visited exactly once to determine its formatted length. The space complexity is O(n) for storing the width of each column.
