Similar Problems

Similar Problems not available

Print Words Vertically - Leetcode Solution

Companies:

LeetCode:  Print Words Vertically Leetcode Solution

Difficulty: Medium

Topics: string array simulation  

Problem statement:

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:

The approach to this problem can be as follows:

  1. Create a list of strings to store each word vertically.
  2. Split the given string s into individual words.
  3. Find the maximum length of the words.
  4. Traverse each character of each word and append it to the corresponding string in the list.
  5. Add spaces to the end of the string if the length of the word is less than the maximum length.

Code:

Here is the Python 3 solution for the problem:

class Solution:
    def printVertically(self, s: str) -> List[str]:
        
        # split the string into individual words
        words = s.split()
        
        # find the maximum length of the words
        max_length = max(len(word) for word in words)
        
        # create a list of strings to store each word vertically
        result = [''] * max_length
        
        # traverse each character of each word and append it to the corresponding string in the list
        for word in words:
            for i, c in enumerate(word):
                result[i] += c
        
        # add spaces to the end of the string if the length of the word is less than the maximum length
        for i in range(max_length):
            result[i] += ' ' * (max_length - len(result[i]))
        
        # remove trailing spaces
        result = [word.rstrip() for word in result]
        
        return result

Time complexity:

The time complexity of the given solution is O(n*m), where n is the number of words in the input string and m is the maximum length of the words.

Space complexity:

The space complexity of the given solution is O(m), where m is the maximum length of the words. This is because we are storing each character of each word vertically in a list of strings.

Print Words Vertically Solution Code

1