Skip to main content
Back to problems
#1324
Medium Algorithms

Print words vertically

Array String Simulation
67.4% acceptance
Feb 25, 2026
824
121
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn print_vertically(s: String) -> Vec<String> {
    let words: Vec<&str> = s.split(' ').collect();
    let max_len = words.iter().map(|w| w.len()).max().unwrap_or(0);
    let mut res = Vec::new();
    for col in 0..max_len {
      let mut row = String::new();
      for word in &words {
        if col < word.len() {
          row.push(word.as_bytes()[col] as char);
        } else {
          row.push(' ');
        }
      }
      // Trim trailing spaces
      let trimmed = row.trim_end().to_string();
      res.push(trimmed);
    }
    res
  }
}