LeetCode Problem Workspace
Print Words Vertically
Transform a string into vertical columns by arranging each word character in array positions while trimming trailing spaces.
3
Topics
4
Code langs
3
Related
Practice Focus
Medium · Array plus String
Answer-first summary
Transform a string into vertical columns by arranging each word character in array positions while trimming trailing spaces.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Array plus String
To solve Print Words Vertically, split the input string into words, determine the maximum word length, and iterate column by column to assemble vertical strings. Each column represents characters from all words at that index, adding spaces where shorter words end, but trimming trailing spaces to match the problem's requirement. This approach leverages array and string manipulation to simulate vertical printing accurately.
Problem Statement
Given a string s consisting of uppercase English letters and spaces, return the words of s printed vertically in the order they appear. Each word occupies one column, and the vertical representation combines characters from each word at the same index.
Output the result as a list of strings where each string represents a vertical slice of the words. Fill empty positions with spaces only when necessary, and remove trailing spaces from each string. Ensure that columns do not exceed the maximum word length and maintain the original word order.
Examples
Example 1
Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Each word is printed vertically.
"HAY"
"ORO"
"WEU"
Example 2
Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE"," T"]
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"]
Example details omitted.
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 Approach
Split words and determine column count
First, split the input string s into an array of words. Identify the longest word to determine the total number of columns needed. Each column will correspond to a character index across all words.
Build vertical strings using array iteration
Iterate from index 0 to maximum word length minus one. For each index, traverse all words and append the character if available; otherwise, append a space. This constructs each vertical string in the output array.
Trim trailing spaces to finalize output
After building each vertical string, remove trailing spaces to satisfy problem constraints. This ensures the output matches expected formatting and avoids common off-by-one failures when shorter words do not extend to the maximum length.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
Time complexity is O(n * m), where n is the number of words and m is the length of the longest word, because each character in each word is visited once. Space complexity is also O(n * m) due to storing vertical strings in the result array.
What Interviewers Usually Probe
- Are you considering varying word lengths for column generation?
- How do you handle trailing spaces when shorter words end before longer ones?
- Can you simulate the vertical printing without using extra nested arrays?
Common Pitfalls or Variants
Common pitfalls
- Not trimming trailing spaces, resulting in incorrect output format.
- Assuming all words have equal length, causing index out-of-range errors.
- Appending characters in the wrong order and losing the original word sequence.
Follow-up variants
- Return words rotated diagonally instead of strictly vertical columns.
- Handle lowercase and mixed-case letters while preserving original formatting.
- Support multiple spaces between words and preserve spacing alignment in output.
FAQ
How do I handle words of different lengths in Print Words Vertically?
Use the length of the longest word to define columns and add spaces for shorter words, trimming trailing spaces afterward.
Can this problem be solved without using nested loops?
Nested iteration over word indices and word array is the simplest approach; alternative methods still mimic this column-by-column access.
Why are trailing spaces a concern in vertical word printing?
Trailing spaces are not allowed by the problem constraints; forgetting to trim them results in failed test cases.
Does the solution rely on any specific data structures?
A simple array of strings suffices, leveraging index access for array plus string manipulation.
Is this problem pattern commonly seen in interviews?
Yes, it tests array and string manipulation with simulation patterns, specifically handling vertical alignment of character sequences.
Solution
Solution 1
#### Python3
class Solution:
def printVertically(self, s: str) -> List[str]:
words = s.split()
n = max(len(w) for w in words)
ans = []
for j in range(n):
t = [w[j] if j < len(w) else ' ' for w in words]
while t[-1] == ' ':
t.pop()
ans.append(''.join(t))
return ansContinue Topic
array
Practice more edge cases under the same topic.
arrow_forwardauto_awesomeContinue Pattern
Array plus String
Expand the same solving frame across more problems.
arrow_forwardsignal_cellular_altSame Difficulty Track
Medium
Stay on this level to stabilize interview delivery.
arrow_forward