algoadvance

Leetcode 2639. Find the Width of Columns of a Grid

Problem Statement:

You are given a 2D grid of integers grid. A column’s width is defined as the maximum length of any integer in that column. Return an array of integers where each element represents the width of the respective column in the grid.

Clarifying Questions:

  1. Input Constraints: What are the constraints on the size of the grid and the range of the integers in the grid?
    • Let’s assume typical constraints for grid-related problems: the grid size can be up to 1000x1000 and integer values can range between -10^9 and 10^9.
  2. Leading Zeros: Are we concerned with leading zeros in integer representations?
    • No, we are dealing with direct integer lengths, which means we consider the natural representation of numbers, without leading zeros.
  3. Output Format: The output should be a vector of integers, right?
    • Yes, a vector where each element corresponds to the width of the respective column.

Strategy:

  1. Determine Number Length: The width of each integer can be determined by converting it to a string and checking its length.
  2. Column-wise Iteration: Iterate over each column and find the maximum width (length of the string representation of each integer).
  3. Comparison: During iteration, compare the length of the current integer with the current maximum width for that column and update accordingly.
  4. Result Collection: Collect the maximum width for each column in a result vector and return it.

Code:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

vector<int> findColumnWidth(vector<vector<int>>& grid) {
    if (grid.empty() || grid[0].empty()) return {};

    int rows = grid.size();
    int cols = grid[0].size();
    vector<int> columnWidths(cols, 0);

    for (int col = 0; col < cols; ++col) {
        for (int row = 0; row < rows; ++row) {
            int numWidth = to_string(grid[row][col]).length();
            columnWidths[col] = max(columnWidths[col], numWidth);
        }
    }
    return columnWidths;
}

int main() {
    vector<vector<int>> grid = {
        {123, 4, -56},
        {78, 9012, 3},
        {45, 6, 789}
    };

    vector<int> result = findColumnWidth(grid);
    for (int width : result) {
        cout << width << " ";
    }
    return 0;
}

Time Complexity:

This approach ensures that the length of the output list matches the number of columns in the provided grid, and each element correctly represents the maximum width of the integers in its respective column.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI