Peeush Agarwal > Engineer. Learner. Builder.

I am a Machine Learning Engineer passionate about creating practical AI solutions using Machine Learning, NLP, Computer Vision, and Azure technologies. This space is where I document my projects, experiments, and insights as I grow in the world of data science.

View on GitHub

Intuition

To solve the ZigZag conversion problem, I first thought about simulating the process of writing the string in a zigzag pattern row by row. The main challenge is to determine the direction of traversal (down or up) and to collect characters for each row accordingly.

Approach

Complexity

Code

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if (numRows == 1) or (len(s) <= numRows):
            return s

        rows = {}
        cur_row = 0
        step = 1

        for c in s:
            rows[cur_row] = rows.get(cur_row, [])
            rows[cur_row].append(c)
            cur_row += step

            if (cur_row <= 0) or (cur_row >= numRows - 1):
                step = -1 * step

        ans = []
        for r in range(numRows):
            ans.extend(rows[r])

        return "".join(ans)

Back to Problem Statement