Approaches
💡
Intuition
Time O(m * n)Space O(n)
In this approach, we will check each column individually by iterating through all the rows. For each number, we will calculate its length and keep track of the maximum length found in that column.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array 'ans' of size n with all zeros to store the maximum widths of each column.
- 2Step 2: For each column, iterate through all rows to find the maximum length of the integers in that column.
- 3Step 3: For each integer, calculate its length based on whether it is negative or non-negative, and update the maximum length for that column.
solution.py10 lines
1# Full working Python code
2
3def findColumnWidths(grid):
4 m, n = len(grid), len(grid[0])
5 ans = [0] * n
6 for j in range(n):
7 for i in range(m):
8 length = len(str(abs(grid[i][j]))) + (1 if grid[i][j] < 0 else 0)
9 ans[j] = max(ans[j], length)
10 return ansℹ
Complexity note: We iterate through each column and each row, leading to a time complexity of O(m * n). The space complexity is O(n) for the output array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.