Problem

Given a string s. Return all the words vertically in the same order in which they appear in s. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word.

Examples

Example 1

1
2
3
4
5
6
Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically. 
 "HAY"
 "ORO"
 "WEU"

Example 2

1
2
3
4
5
6
Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE","   T"]
Explanation: Trailing spaces is not allowed. 
"TBONTB"
"OEROOE"
"   T"

Example 3

1
2
Input: s = "CONTEST IS COMING"
Output: ["CIC","OSO","N M","T I","E N","S G","T"]

Constraints

  • 1 <= s.length <= 200
  • s contains only upper case English letters.
  • It’s guaranteed that there is only one space between 2 words.

Solution

Method 1 – Simulate Columns by Index

Intuition

We can treat the words as columns and build each vertical word by iterating over each character index. Pad with spaces as needed, and strip trailing spaces at the end.

Approach

  1. Split the string into words.
  2. For each character index up to the longest word, build a string by taking the character at that index from each word (or a space if the word is too short).
  3. Strip trailing spaces from each vertical word.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
public:
    vector<string> printVertically(string s) {
        vector<string> words;
        istringstream iss(s);
        string w;
        int maxlen = 0;
        while (iss >> w) { words.push_back(w); maxlen = max(maxlen, (int)w.size()); }
        vector<string> res;
        for (int i = 0; i < maxlen; ++i) {
            string col;
            for (auto& word : words) col += i < word.size() ? word[i] : ' ';
            while (!col.empty() && col.back() == ' ') col.pop_back();
            res.push_back(col);
        }
        return res;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
func printVertically(s string) []string {
    words := strings.Fields(s)
    maxlen := 0
    for _, w := range words {
        if len(w) > maxlen { maxlen = len(w) }
    }
    res := []string{}
    for i := 0; i < maxlen; i++ {
        col := ""
        for _, w := range words {
            if i < len(w) { col += string(w[i]) } else { col += " " }
        }
        res = append(res, strings.TrimRight(col, " "))
    }
    return res
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.util.*;
class Solution {
    public 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 i = 0; i < maxlen; ++i) {
            StringBuilder col = new StringBuilder();
            for (String w : words) col.append(i < w.length() ? w.charAt(i) : ' ');
            int end = col.length();
            while (end > 0 && col.charAt(end-1) == ' ') end--;
            res.add(col.substring(0, end));
        }
        return res;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
    fun printVertically(s: String): List<String> {
        val words = s.split(" ")
        val maxlen = words.maxOf { it.length }
        val res = mutableListOf<String>()
        for (i in 0 until maxlen) {
            var col = ""
            for (w in words) col += if (i < w.length) w[i] else ' '
            res.add(col.rstrip())
        }
        return res
    }
}
private fun String.rstrip() = this.replace(Regex(" +$"), "")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from typing import List
class Solution:
    def printVertically(self, s: str) -> List[str]:
        words = s.split()
        maxlen = max(len(w) for w in words)
        res = []
        for i in range(maxlen):
            col = ''.join(w[i] if i < len(w) else ' ' for w in words).rstrip()
            res.append(col)
        return res
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
impl Solution {
    pub fn print_vertically(s: String) -> Vec<String> {
        let words: Vec<&str> = s.split_whitespace().collect();
        let maxlen = words.iter().map(|w| w.len()).max().unwrap();
        let mut res = Vec::new();
        for i in 0..maxlen {
            let mut col = String::new();
            for w in &words {
                if i < w.len() { col.push(w.chars().nth(i).unwrap()); } else { col.push(' '); }
            }
            while col.ends_with(' ') { col.pop(); }
            res.push(col);
        }
        res
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    printVertically(s: string): string[] {
        const words = s.split(' ');
        const maxlen = Math.max(...words.map(w => w.length));
        const res: string[] = [];
        for (let i = 0; i < maxlen; ++i) {
            let col = '';
            for (const w of words) col += i < w.length ? w[i] : ' ';
            res.push(col.replace(/\s+$/, ''));
        }
        return res;
    }
}

Complexity

  • ⏰ Time complexity: O(W * L) where W is the number of words and L is the max word length.
  • 🧺 Space complexity: O(W * L) for the output.