#1324

Print Words Vertically

Medium
ArrayStringSimulationArrayString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution builds on the brute force approach but uses a more efficient way to handle the vertical construction by directly using a list of strings to store the vertical words, avoiding unnecessary string concatenation.

⚙️

Algorithm

3 steps
  1. 1Step 1: Split the string into words.
  2. 2Step 2: Create a list of empty strings for each vertical word.
  3. 3Step 3: Iterate through each word and character, appending characters to the corresponding vertical word string.
solution.py11 lines
1def printVertically(s):
2    words = s.split()
3    max_length = max(len(word) for word in words)
4    result = [''] * max_length
5    for word in words:
6        for i in range(max_length):
7            if i < len(word):
8                result[i] += word[i]
9            else:
10                result[i] += ' '
11    return [word.rstrip() for word in result]

Complexity note: The time complexity is O(n) because we iterate through each character of the words exactly once. The space complexity is O(n) due to the storage of the result strings.

  • 1Understanding how to handle spaces is crucial for formatting the output correctly.
  • 2Recognizing the maximum length of words helps in determining the vertical structure.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.