# Well commented python solution with examples

• If you draw the problem in a little different way it becomes much easier to tackle:

``````# EXAMPLE
# Inputs: "PAYPALISHIRING", 4
#
# buffer 1 (P           (I         (N
# buffer 2   A       L]   S      I]  G)
# buffer 3    Y   [A       H   [R
# buffer 4     P)           I)
#
# () - zig downwards
# [] - zag upwards
#
# append all buffers sequentially afterwards

class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""

# create buffers for each row
results = ["" for r in range(0, numRows)]
i = 0

# iterate over whole string
while i < len(s):

# zig downwards if string is not fully traversed yet - () part from example
for down_idx in range(0, numRows):
if i < len(s):
results[down_idx] += s[i]
i += 1

# zag upwards if string is not fully traversed yet - [] part from example
for up_idx in range(numRows - 2, 0, -1): # minus 2 since two letters at tails are "eaten" when moving downwards
if i < len(s):
results[up_idx] += s[i]
i += 1

zigzag = ""
for result in results:
zigzag += result

return zigzag
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.