LeetCode 1324: Print Words Vertically Solution

Master LeetCode problem 1324 (Print Words Vertically), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1324. Print Words Vertically

Problem Explanation

Explanation

To solve this problem, we can follow these steps:

  1. Split the input string s into a list of words.
  2. Find the maximum length among all the words.
  3. Iterate over each character position from 0 to the maximum word length.
  4. For each character position, iterate over all the words and add the character at that position to the result string for that column.
  5. Trim any trailing spaces from the result strings.

Time complexity: O(n * m), where n is the number of words and m is the length of the longest word.
Space complexity: O(n * m), for storing the output list of strings.

Solution Code

class Solution {
    public List<String> printVertically(String s) {
        List<String> words = Arrays.asList(s.split(" "));
        int maxLen = words.stream().mapToInt(String::length).max().getAsInt();
        List<String> result = new ArrayList<>();
        
        for (int i = 0; i < maxLen; i++) {
            StringBuilder sb = new StringBuilder();
            for (String word : words) {
                sb.append(i < word.length() ? word.charAt(i) : " ");
            }
            result.add(sb.toString().replaceAll("\\s+$", ""));
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1324 (Print Words Vertically)?

This page provides optimized solutions for LeetCode problem 1324 (Print Words Vertically) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1324 (Print Words Vertically)?

The time complexity for LeetCode 1324 (Print Words Vertically) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1324 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1324 in Java, C++, or Python.

Back to LeetCode Solutions