{x}
blog image

Print Words Vertically

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.

 

Example 1:

Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically. 
 "HAY"
 "ORO"
 "WEU"

Example 2:

Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE","   T"]
Explanation: Trailing spaces is not allowed. 
"TBONTB"
"OEROOE"
"   T"

Example 3:

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 Explanation

The problem asks to print the words in a given string vertically. The output should be a list of strings, where each string represents a vertical column of characters. Trailing spaces are not allowed in the output strings.

Approach

  1. Split the string: The input string s is split into a list of words using the split() method (or equivalent in other languages).

  2. Find maximum word length: The maximum length among all words is determined. This is important to know how many rows we will need in our vertical output.

  3. Iterate through columns: The code iterates through each column (from index 0 to the maximum word length).

  4. Build each column string: For each column index, it iterates through the words. If a word has a character at the current column index, it's added to the column string; otherwise, a space is added.

  5. Remove trailing spaces: After building each column string, trailing spaces are removed.

  6. Append to result: The column string is added to the result list.

  7. Return the result: The list of column strings is returned as the final answer.

Time and Space Complexity Analysis

Time Complexity: O(M * N), where N is the number of words and M is the maximum length of a word. This is because we iterate through each word (N) for each column (up to M).

Space Complexity: O(M * N). The space used is dominated by the result list, which can store up to M * N characters in the worst case (all words have maximum length). The intermediate strings used for building the columns also contribute to this space complexity.

Code in Different Languages

The code examples in Python, Java, C++, and Go all follow the same approach described above. They differ only in syntax and specific library functions used. Each example demonstrates efficient string manipulation to achieve the desired output. The use of StringBuilder (Java) or similar techniques helps optimize string concatenation performance.