Zigzag Conversion

Key Idea

Solution

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        # Inputs: s, numRows
        # Output: str
        # Example
            # Inputs: s = "PAYPALISHIRING", numRows = 3
            # Output: "PAHNAPLSIIGYIR"
        
        # Example 2:
            # Input: s = "PAYPALISHIRING", numRows = 4
            # Output: "PINALSIGYAHRPI"
            # Explanation:
            # P     I    N
            # A   L S  I G
            # Y A   H R
            # P     I
        # Example 3:
            # Input: s = "A", numRows = 1
            # Output: "A"

        # Edge Case
        if numRows == 1:
            return s
        
        # Initialize
        rows = [""] * numRows

        current_row = 0
        direction = 1

        for character in s:
            rows[current_row] += character
            if current_row == 0 :
                direction = 1
            elif current_row == numRows - 1:
                direction = -1
            
            # Move 
            current_row += direction
        # Join all
        return "".join(rows)

Complexity