# 6 ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

```
P   A   H   N
A P L S I I G
Y   I   R
```

And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:

```
string convert(string text, int nRows);
```

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

```cpp
string convert(string s, int numRows) {
    if (s.empty())
        return s;

    vector<vector<char>> zigs(numRows);
    int row = 0, col = 0;

    // 0 1 2 1 0 1 2 0 1 2 0 1 2…
    /*
    P   A   H   N
    A P L S I I G
    Y   I   R
    */
    int cur_index = 0;
    int reset = 1;
    while (cur_index < s.length()) {

        for (row; row < numRows && cur_index < s.length(); row++) {
            zigs.at(row).push_back(s.at(cur_index++));
        }

        for (row = row - 2; row >= 0 && cur_index < s.length(); row--) {
            zigs.at(row).push_back(s.at(cur_index++));
        }
        row = reset;
    }

    //print2d(zigs);

    string ret_str;
    int iter = 0;
    int where = 0;
    for (int i = 0; i < zigs.size(); i++) {
        for (int j = 0; j < zigs.at(i).size(); j++) {
            ret_str.insert(where++, string(1, zigs.at(i).at(j)));
        }
        iter++;
    }

    return ret_str;
}



int main() {
    string conv = "PAYPALISHIRING";
    cout << convert(conv, 3) << endl;
    pause();



}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/6_zigzag_conversion.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
