The “Zigzag Conversion” problem on LeetCode is as follows:
Convert a given string s
to a new string in a “zigzag” pattern, given a specified number of rows, numRows
.
Here’s an example of how the conversion works with s = "PAYPALISHIRING"
and numRows = 4
:
P I N
A L S I G
Y A H R
P I
The output for this example would be “PINALSIGYAHRPI”.
s
and an integer numRows
, return the string s
written in a zigzag pattern on a given number of rows.numRows
is 1?
s
be?
numRows
is 1 or the length of the string is less than numRows
, return the string itself as there is no “zigzag” possible.def convert(s: str, numRows: int) -> str:
if numRows == 1 or numRows >= len(s):
return s
# Initialize the rows
rows = [''] * numRows
curRow = 0
goingDown = False
# Traverse the string character by character
for char in s:
rows[curRow] += char
if curRow == 0 or curRow == numRows - 1:
goingDown = not goingDown
curRow += 1 if goingDown else -1
# Combine the rows
return ''.join(rows)
# Example usage
s = "PAYPALISHIRING"
numRows = 4
result = convert(s, numRows)
print(result) # Expected "PINALSIGYAHRPI"
The time complexity of this solution is O(n), where n is the length of the input string s
. This is because we process each character in the string exactly once.
The space complexity is O(n) as well, since we are storing intermediate results for each of the rows in the list, and then concatenating these at the end to create the final result.
Let me know if you need further clarifications or modifications!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?