Domain 2MediumMEDIUM

Print Words Vertically

LeetCode problem 1324: Print Words Vertically (medium).

Domain: medium•Updated: 2026-09-14
#String

Problem Breakdown

We need to transform a horizontal string of words into vertical columns where each character from every word aligns at the same index across different rows.

  • Input: A single string s containing uppercase letters and spaces separating words (single space between words).
  • Output: A list of strings, representing each column as a row in our output matrix.
  • Key Constraint: Trailing spaces are strictly forbidden on any resulting string. However, leading spaces must be preserved if shorter words exist at the beginning of that vertical slice.
  • Edge Cases to Consider:
    • Words with different lengths (dictates number of rows).
    • Shortest word vs Longest word alignment (padding logic).
    • Single word input (max length = len(word), only one row).

Intuition

A brute force approach might try to iterate through the string character by character and build columns, but managing indices across variable-length words is complex.

  • Brute Force: Attempting to construct each column directly without splitting first would require tracking word boundaries manually for every index. This leads to O(N^2) complexity in worst cases due to repeated scanning or inefficient padding logic.
  • Key Insight: Treat the input as a matrix where rows are characters and columns represent words (conceptually). We want to read this column-by-column but output row-by-row.
  • Optimal Approach: Split s into individual words first. Determine the maximum word length, which defines how many vertical strings we need. Iterate through each index from 0 up to max_length - 1. For every index (vertical position), construct a string by taking the character at that index for each valid word; if a word is too short, append a space ' '. Finally, strip trailing spaces from this constructed row before adding it to our result list.

Approach

  1. Split: Use s.split() to get a list of words (handles multiple spaces automatically though constraints say single).
  2. Determine Rows: Calculate the length of the longest word (max_len). This is the number of strings in our output list.
  3. Iterate Columns: Loop from index i = 0 to max_len - 1.
  4. Build Row String: For each column index i:
    • Initialize an empty string or list for current row characters.
    • Iterate through every word in the split list.
    • If the word’s length is greater than i, append word[i] to our temporary buffer.
    • Otherwise, if the word ends before index i, append a space ' '.
  5. Clean Row: Join characters into a string and apply .rstrip() to remove trailing spaces (as per constraints).
  6. Store Result: Append cleaned row to result list.

Complexity Analysis

  • Time Complexity: O(N)O(N), where NN is the length of s. We iterate through each character in every word exactly once during construction. The number of rows times words roughly equals total characters plus padding spaces which sum up linearly with input size.
  • Space Complexity: O(N)O(N). We store the result list and intermediate strings proportional to the output size, which is bounded by the input length (excluding trailing spaces).

Solution

def printVertically(s: str):
    words = s.split()
    
    # If no words exist (edge case though constraints say len >= 1)
    if not words:
        return []
        
    max_len = len(max(words, key=len))
    result = []

    for i in range(max_len):
        row_chars = []
        for word in words:
            # If index exists in this word, take char; else space
            if i < len(word):
                row_chars.append(word[i])
            else:
                row_chars.append(' ')
        
        # Join and remove trailing spaces as required by problem statement
        result.append("".join(row_chars).rstrip())

    return result

Edge Cases Handled

  • Varying Word Lengths: The loop runs up to the longest word’s length. Shorter words contribute a space for missing indices, ensuring alignment (e.g., Example 2 and 3).
  • Trailing Spaces: .rstrip() ensures no output string ends with spaces, satisfying constraints while preserving necessary leading padding from shorter words.
  • Single Word Input: max_len equals the word length; loop runs once per character of that single word (plus trailing space handling if logic allowed, but here only one row).
  • Empty String/No Words: Handled via check or implicit behavior given constraints (1≤s.length1 \le s.length), though code returns empty list gracefully.