6. ZigZag Conversion

Approach 1: Iterate character by character

class Solution:
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows<=1: return s
        ans=[""]*numRows
        i=0
        for c in s:
            ans[i]+=c
            if i==numRows-1:
                d=-1
            if i==0:
                d=1
            i+=d
        return ''.join(ans)

Iterate over the characters one by one, while maintaining a counter for current row number. Keep incrementing the counter one by one and when you reach numRows start subtracting 1 each time, and append the character to the calculated index and return the join of all these rows as a string

Time Complexity: O(n)

Space Complexity: O(n)

Last updated