Grokking 75: Top Coding Interview Questions
0% completed
Solution: Zigzag Conversion
Problem Statement
Given a string s and a numRows integer representing the number of rows, write the string in a zigzag pattern on the given number of rows and then read it line by line, and return the resultant string.
The zigzag pattern means writing characters in a diagonal down-and-up fashion. For example, given the string "HELLOPROGRAMMING" and 4 rows, the pattern would look like:
H R M
E P O M I
L O G A N
L R G
Reading it line by line gives us "HRMEPOMILOGANLRG".
Examples
Example 1:
- Input:
.....
.....
.....
Like the course? Get enrolled and start learning!
NITIN KUMAR
· 3 months ago
in the python solution the complexity is not O(n ) but O(n^2 ) , that's is because every time we do
# Append the character to the current row rows[currentRow] += c
it's taking O( n) time not O(1) , for python we should use list instead of string and then concatinate it at the end.
python solution:
class Solution:
def create_zig_zag(self, s: str, rows : int) -> list[str]:
res = [[] for _ in range(rows)]
i = 0
going_down = False
for ch in s:
res[i].append(ch)
if i == 0 or i == (rows - 1):
going_down = not going_down
i += 1 if going_down else -1
return res
def convert(self, s: str, rows: int) -> str:
# ToDo: Wrte Your