Python 2639.py
class Solution:
def findColumnWidth(self, grid: List[List[int]]) -> List[int]:
result = []
for g in grid:
for i, n in enumerate(g):
size = len(str(n))
if i == len(result):
result.append(size)
else:
result[i] = max(result[i], size)
return result
Difficulty
and has an acceptance rate of about 71% (50k+ submissions).
Typical patterns to solve this problem:
- Array
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the maximum display width required for each column of a two-dimensional integer matrix. By converting each integer to its string representation, the algorithm determines how many characters are needed to render the value and records the largest width observed per column. The final output is a list where each element corresponds to a column index and contains the width needed to accommodate the widest entry in that column.
Core Logic
The method begins by initializing an empty list called result. This list will grow dynamically as the algorithm encounters new columns while iterating over the rows of the input grid.
result = []
A nested loop processes the grid row by row. The outer loop iterates over each row g in grid.
for g in grid:
Inside the outer loop, enumerate supplies both the column index i and the integer value n for each element of the current row. Using enumerate eliminates the need for a separate counter variable and keeps the code concise.
for i, n in enumerate(g):
For each integer n, the algorithm converts it to a string and measures its length. This length, stored in size, reflects the number of characters required to display the integer, including a leading minus sign for negative numbers.
size = len(str(n))
The next step decides whether the current column index i already has an entry in result. If i equals the current length of result, the column has not been seen before, and the algorithm appends the newly computed size as the initial width for that column.
if i == len(result):
result.append(size)
If the column already exists in result, the algorithm updates the stored width by taking the maximum of the existing width and the newly computed size. This ensures that result[i] always reflects the widest value encountered so far in column i.
else:
result[i] = max(result[i], size)
After all rows have been processed, the method returns the populated result list, which now contains the required widths for each column.
return result
Edge-Case Handling
The implementation gracefully manages several edge conditions without additional branching:
-
Empty grid - When
gridis an empty list, the outer loop never executes, leavingresultempty. The method returns an empty list, correctly indicating that there are no columns to size. -
Rows of differing lengths - Because the inner loop uses
enumerateon each row independently, columns are discovered on the fly. If a later row contains more columns than earlier rows, the conditioni == len(result)triggers anappend, extendingresultto accommodate the new column. Conversely, if a row is shorter, the inner loop simply iterates over the existing columns present in that row, leaving the widths of missing columns unchanged. -
Negative numbers - Converting a negative integer to a string includes the minus sign, so
len(str(n))naturally accounts for the extra character. The algorithm therefore allocates sufficient width for negative values without special handling. -
Zero and large integers - Zero converts to
"0"with length one, while arbitrarily large integers produce longer strings. Themaxcomparison ensures that the widest representation, regardless of magnitude, determines the final column width. -
Non-integer types - The type hint
List[List[int]]indicates that the input should consist of integers. If other numeric types (e.g., booleans) appear, Python’sstrconversion still yields a string representation, and the length calculation proceeds without error, preserving the method’s robustness.
Performance Optimizations
The algorithm exhibits several efficiency-focused choices:
-
Single pass over the data - By iterating through each element exactly once and updating the result in place, the method avoids any secondary scans or auxiliary data structures. This reduces overhead and keeps the runtime proportional to the total number of elements.
-
In-place updates - The use of
result[i] = max(result[i], size)modifies the existing list rather than creating a new list for each row. This minimizes memory allocations and leverages Python’s mutable list semantics. -
Lazy column expansion - The conditional
if i == len(result)appends only when a new column is first encountered. This avoids pre-allocating a list of a fixed size based on the maximum row length, which could be wasteful if many rows are shorter. -
Direct string length computation - Converting each integer to a string and measuring its length is a straightforward O(1) operation per element. The algorithm does not perform any additional parsing or arithmetic to determine digit count, which keeps the inner loop lightweight.
-
Enumerate for index retrieval - Using
enumerateeliminates the need for manual index tracking, reducing the chance of off-by-one errors and allowing the interpreter to handle index incrementation efficiently.
Overall, the method delivers a concise solution that adapts to varying grid shapes, handles special numeric cases naturally, and operates with minimal computational and memory overhead.
ELI5 - Simplified Explanation
Imagine there is a big grid made of squares, and each square has a number inside it. The goal is to figure out how wide each column of numbers is. A column is like a vertical line of squares going from the top to the bottom.
First, an empty list is created to hold the width of every column. Think of this list as a shelf where each spot holds the size of a column.
The computer looks at every row in the grid one by one. For every number in those rows, the computer counts how many digits the number has. For example, the number five has one digit, but the number ten has two digits.
When the computer looks at a number, it checks which column that number belongs to. If it is the first time seeing a column, the computer puts the size of that number onto the shelf. If the computer has already seen that column before, it compares the new number to the size already on the shelf. It keeps the biggest number because a column must be wide enough to fit its largest number.
After checking every single number in the grid, the shelf is finished and shows the final width for every column.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | Java | Python | C++ | TS | |||
| WalkCCC | Java | Python | C++ | |||||
| leetcode.ca | Java | Python | Go | C++ | Rust | TS | ||
| Progiez | Java | Python | C++ | |||||
| github | charles-wangkai | Java | ||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| muhammadfarhankt | Go | |||||||
| varunu28 | Java | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| muhammadfarhankt | Go | |||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 2048: Next Greater Numerically Balanced Number
Solved On The Same Day
- problem 2243: Calculate Digit Sum of a String
- problem 2678: Number of Senior Citizens
- problem 2733: Neither Minimum nor Maximum
- problem 2740: Find the Value of the Partition
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality