Solving Leetcode Interviews in Seconds with AI: Print Words Vertically
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1324" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
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. Example 1: Input: s = "HOW ARE YOU" Output: ["HAY","ORO","WEU"] Explanation: Each word is printed vertically. "HAY" "ORO" "WEU" Example 2: Input: s = "TO BE OR NOT TO BE" Output: ["TBONTB","OEROOE"," T"] Explanation: Trailing spaces is not allowed. "TBONTB" "OEROOE" " T" Example 3: Input: s = "CONTEST IS COMING" Output: ["CIC","OSO","N M","T I","E N","S G","T"] Constraints: 1 <= s.length <= 200 s contains only upper case English letters. It's guaranteed that there is only one space between 2 words.
Explanation
Here's the breakdown of the solution:
- Split the string into words: The input string is split into a list of individual words.
- Determine the maximum length: The length of the longest word is found. This determines the number of rows in our output.
Build vertical words: Iterate through the characters column-wise. If a word has fewer characters than the current column index, add a space. Otherwise, append the character at that index to the vertical word being constructed. Remove trailing spaces before appending to the final result.
Runtime Complexity: O(N*M), Storage Complexity: O(N*M) where N is the number of words, and M is the length of the longest word.
Code
def vertical_words(s: str) -> list[str]:
"""
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.
"""
words = s.split()
max_len = max(len(word) for word in words) if words else 0
result = []
for i in range(max_len):
vertical_word = ""
for word in words:
if i < len(word):
vertical_word += word[i]
else:
vertical_word += " "
# Remove trailing spaces
vertical_word = vertical_word.rstrip()
result.append(vertical_word)
return result