#6
Zigzag Conversion
MediumStringHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Hash Map)★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a hash map to store characters in their respective rows, allowing for efficient access and concatenation. This method significantly reduces the number of passes needed to construct the final string.
⚙️
Algorithm
3 steps- 1Step 1: Create a list of strings (or a hash map) to hold characters for each row.
- 2Step 2: Iterate through the string, placing each character in the appropriate row based on the current direction.
- 3Step 3: After filling all rows, concatenate the strings to form the final output.
solution.py20 lines
1# Full working Python code with comments
2
3def convert(s: str, numRows: int) -> str:
4 if numRows == 1 or numRows >= len(s):
5 return s
6
7 rows = [''] * numRows
8 current_row = 0
9 going_down = False
10
11 for char in s:
12 rows[current_row] += char
13 if current_row == 0:
14 going_down = True
15 elif current_row == numRows - 1:
16 going_down = False
17 current_row += 1 if going_down else -1
18
19 return ''.join(rows)
20ℹ
Complexity note: The time complexity is O(n) because we only need to traverse the string once. The space complexity is O(n) due to the storage of characters in the rows.
- 1The zigzag pattern can be visualized as a wave, where characters are placed in a downward slope and then an upward slope. Recognizing this pattern helps in determining the row placement of each character.
- 2Understanding the direction of traversal (down and up) is crucial. This can be managed with a simple boolean flag that toggles when reaching the top or bottom row.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.