LeetCode 6 -ย ZigZag Conversion
Intuition
The key insight is recognising that we only need to track which row each character belongs to in the final zigzag pattern. So the most important decision is in the data structure; rather than building the entire 2D structure, we just need to determine which row a particular character belongs to, and we can achieve this using a counter that alternates direction at the boundaries.
Approach
- Append it to the current row
- Move to the next row (increment if going down, decrement if going up)
- Change direction when hitting boundaries (i equals numRows or -1)
Complexity
Solution
class Solution:
ย ย def convert(self, s: str, numRows: int) โ str:
ย ย ย ย if numRows < 2: # no zigzag if not at least 2 rows
ย ย ย ย ย ย return s
ย ย ย ย row_values: list[list[str]] = [[] for i in range(numRows)]
ย ย ย ย going_down: bool = True
ย ย ย ย i: int = 0 # counter to track the row (dict key) adding char to
ย ย ย ย for char in s:
ย ย ย ย ย ย row_values[i].append(char)
ย ย ย ย ย ย if going_down:
ย ย ย ย ย ย ย ย i += 1
ย ย ย ย ย ย else:
ย ย ย ย ย ย ย ย i -= 1
ย ย ย ย ย ย if i == numRows:
ย ย ย ย ย ย ย ย going_down = False
ย ย ย ย ย ย ย ย i = numRows - 2 # skip bottom corner v case
ย ย ย ย ย ย if i == -1:
ย ย ย ย ย ย ย ย going_down = True
ย ย ย ย ย ย ย ย i = 1 # skip top corner v case
ย ย ย ย final_string: list = []
ย ย ย ย for row in row_values:
ย ย ย ย ย ย final_string.extend(row)
ย ย ย ย return ''.join(final_string)


balas pos