Skip to content
LC-0006 Medium LeetCode

6. Zigzag Conversion

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 51% Topics: String
View full problem on LeetCode

Reading material

Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(1)

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s
        step, zigzag = 2 * numRows - 2, ""
        for i in xrange(numRows):
            for j in xrange(i, len(s), step):
                zigzag += s[j]
                if 0 < i < numRows - 1 and j + step - 2 * i < len(s):
                    zigzag += s[j + step - 2 * i]
        return zigzag

Solution from kamyu104/LeetCode-Solutions · MIT