Skip to content

Conversation

@devkumar2313
Copy link
Contributor

@devkumar2313 devkumar2313 commented Oct 2, 2025

Approach

The solution simulates writing the input string in a zigzag pattern across the specified number of rows and then reads it row by row to produce the final output.

  • If numRows is 1 or greater than or equal to the string length, return the input string as is (edge cases).
  • Use a vector of strings to represent each row in the zigzag pattern.
  • Iterate through the string, placing each character in the appropriate row while tracking the current direction (down or up).
  • Change direction when reaching the top or bottom row.
  • Concatenate all rows to form the final result string.

Intuition

The zigzag pattern can be visualized as filling rows downwards and then diagonally upwards. The traversal of the string simulates this pattern, ensuring that each character is placed in the correct row. By storing characters row-wise and then concatenating, we can reconstruct the zigzagged string as required.

Solution in Code (C++)

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1 || numRows >= s.length()) return s;
        vector<string> rows(numRows);
        int currRow = 0, direction = -1;
        for (char c : s) {
            rows[currRow] += c;
            if (currRow == 0 || currRow == numRows - 1) direction *= -1;
            currRow += direction;
        }
        string result;
        for (string& row : rows) result += row;
        return result;
    }
};

Closes #38

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Message that will be displayed on users' first pull request

@SjxSubham SjxSubham added the hacktoberest-accepted hacktoberfest-accepted label Oct 2, 2025
@devkumar2313
Copy link
Contributor Author

is that right

@SjxSubham
Copy link
Owner

@devkumar2313 yes,,, all good

Star the Repo ⭐

Happy HAcktober... keep contributing

@SjxSubham SjxSubham changed the title Create 6.Zigzag Conversion.cpp 6.Zigzag Conversion.cpp Oct 2, 2025
@devkumar2313
Copy link
Contributor Author

I have star the repo

@SjxSubham SjxSubham merged commit 7f6b4c1 into SjxSubham:main Oct 2, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hacktoberest-accepted hacktoberfest-accepted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6. Zigzag Conversion

2 participants