Print Words Vertically

medium string simulation

Problem

You are given a sentence s of uppercase words separated by single spaces (length up to 200). Rewrite it vertically: the i-th output string is built from the i-th character of every word, taken in order. A word that is too short contributes a space at that position so the columns stay aligned.

Interior padding spaces must be kept, but every output string must have its trailing spaces removed.

Inputs = "TO BE OR NOT TO BE"
Output["TBONTB", "OEROOE", " T"]
In column 2 only "NOT" has a third letter, so the spaces before the T are kept and the ones after it are trimmed.

def print_vertically(s):
    words = s.split()
    max_len = max(len(w) for w in words)
    res = []
    for c in range(max_len):
        col = []
        for w in words:
            col.append(w[c] if c < len(w) else " ")
        res.append("".join(col).rstrip())
    return res
function printVertically(s) {
  const words = s.split(" ");
  const maxLen = Math.max(...words.map(w => w.length));
  const res = [];
  for (let c = 0; c < maxLen; c++) {
    let col = "";
    for (const w of words) col += c < w.length ? w[c] : " ";
    res.push(col.replace(/ +$/, ""));
  }
  return res;
}
List<String> printVertically(String s) {
    String[] words = s.split(" ");
    int maxLen = 0;
    for (String w : words) maxLen = Math.max(maxLen, w.length());
    List<String> res = new ArrayList<>();
    for (int c = 0; c < maxLen; c++) {
        StringBuilder col = new StringBuilder();
        for (String w : words)
            col.append(c < w.length() ? w.charAt(c) : ' ');
        int end = col.length();
        while (end > 0 && col.charAt(end - 1) == ' ') end--;
        res.add(col.substring(0, end));
    }
    return res;
}
vector<string> printVertically(string s) {
    vector<string> words;
    stringstream ss(s);
    string w;
    while (ss >> w) words.push_back(w);
    size_t maxLen = 0;
    for (auto& x : words) maxLen = max(maxLen, x.size());
    vector<string> res;
    for (size_t c = 0; c < maxLen; c++) {
        string col;
        for (auto& x : words)
            col += c < x.size() ? x[c] : ' ';
        while (!col.empty() && col.back() == ' ') col.pop_back();
        res.push_back(col);
    }
    return res;
}
Time: O(words · maxLen) Space: O(words · maxLen)