Hey everyone! Mahdi Shamlou here — rolling on with my LeetCode classic problems series 🚀
After [#5 Longest Palindromic Substring (See the list that i solved)], today we’re tackling Problem #6 — Zigzag Conversion (also called ZigZag Conversion) — a cool medium-level problem that feels like drawing a zigzag pattern with letters!
Problem Statement
The string s is written in a zigzag pattern on a given number of rows like this (imagine fixed font):
For s = “PAYPALISHIRING”, numRows = 3:
P A H N
A P L S I I G Y
I R
Read line by line: “PAHNAPLSIIGYIR”
Write a function to convert the string this way given numRows.
Examples:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G Y
A H R
P I
Input: s = "AB", numRows = 2
Output: "AB"
My solution :
The simulation way with direction flip (this felt natural!) I imagined walking down the rows, then up, then down again — like a real zigzag. So I used a list of strings (one per row), a counter for current row, and a direction flag that flips at top/bottom.
class Solution:
def convert(self, s: str, numRows: int) -> str:
result = []
numRows_counter = 0
numRows_counter_way = 1
for i in s:
result.append("") # wait, this was a bug — should init outside!
result[numRows_counter] = str(result[numRows_counter]) + str(i)
if numRows_counter + 1 == numRows:
numRows_counter_way = -1
if numRows_counter - 1 < 0:
numRows_counter_way = +1
if numRows_counter_way == 1:
numRows_counter = numRows_counter + 1
else:
numRows_counter = numRows_counter - 1
final_res = ""
for i in result:
final_res = final_res + i
print(result)
return final_res
Note: In my first run I had result = [] and appended empty string each time — that’s not correct! (It would create too many empty slots.) The proper way is to initialize result = [“”] * numRows outside the loop. But hey, this direction-flip idea still clicked for me after fixing that 😅
My repo (all solutions are here):
GitHub — mahdi0shamlou/LeetCode: Solve LeetCode Problems
What about you? Did you simulate the zigzag with rows like me, or did you go for the math formula way (cycle length = 2*numRows-2)? Any funny bugs you hit on this one?
Share in the comments — I read everything! 🚀
And honestly… after seeing “PINALSIGYAHRPI” come out correctly I just sat there grinning like an idiot — that zigzag finally made sense in code! 😂 Here’s me right after it worked:
Connect with me:
🔗 LinkedIn: https://www.linkedin.com/in/mahdi-shamlou-3b52b8278
📱 Telegram: https://telegram.me/mahdi0shamlou
📸 Instagram: https://www.instagram.com/mahdi0shamlou/
Author: Mahdi Shamlou | مهدی شاملو


Top comments (0)