Print Concatenation of Zig-Zag String in 'n' Rows

Last Updated : 1 Jul, 2026

Given a string and an integer n representing the number of rows, write the string in a row-wise Zig-Zag pattern with n rows. Return the string formed by concatenating the characters of all rows from top to bottom.

Examples: 

Input: s = "ABCDEFGH", n = 2
Output: "ACEGBDFH"
Explanation: Let us write input strings in Zig-Zag fashion in 2 rows.

2

Now concatenate the two rows and ignore spaces in every row. We get "ACEGBDFH".

Input: s = "GEEKSFORGEEKS", n = 3
Output: "GSGSEKFREKEOE"
Explanation: Let us write input strings in Zig-Zag fashion in 3 rows.

1

Now concatenate the two rows and ignore spaces in every row. We get "GSGSEKFREKEOE".

Try It Yourself
redirect icon

[Naive Approach] Build Zig-Zag Pattern Using Matrix - O(n × |s|) Time and O(n × |s|) Space

The idea is to explicitly construct the Zig-Zag pattern in a 2D matrix. We place each character of the string at its correct position while moving downward and diagonally upward. After building the pattern, we traverse the matrix row by row and concatenate all non-empty characters to form the final string.

C++
#include <iostream>
#include <vector>
using namespace std;

string convert(string &s, int n)
{

    // A single row produces the same string.
    if (n <= 1)
        return s;

    int len = s.size();

    // Matrix used to store the Zig-Zag pattern.
    vector<vector<char>> mat(n, vector<char>(len, '\0'));

    int row = 0, col = 0;
    int idx = 0;

    while (idx < len)
    {

        // Fill downward.
        while (row < n && idx < len)
        {
            mat[row][col] = s[idx++];
            row++;
        }

        row -= 2;
        col++;

        // Fill diagonally upward.
        while (row > 0 && idx < len)
        {
            mat[row][col] = s[idx++];
            row--;
            col++;
        }
    }

    // Concatenate all rows.
    string res;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < len; j++)
        {
            if (mat[i][j] != '\0')
                res.push_back(mat[i][j]);
        }
    }

    return res;
}

// Driver Code
int main()
{
    string s = "GEEKSFORGEEKS";
    int n = 3;

    cout << "\"" << convert(s, n) << "\"" << endl;

    return 0;
}
Java
class GFG {

    static String convert(String s, int n)
    {

        // A single row produces the same string.
        if (n <= 1)
            return s;

        int len = s.length();

        // StringBuilders used to store the Zig-Zag pattern.
        StringBuilder[] rows = new StringBuilder[n];
        for (int i = 0; i < n; i++)
            rows[i] = new StringBuilder();

        int row = 0;
        int idx = 0;

        while (idx < len) {

            // Fill downward.
            while (row < n && idx < len) {
                rows[row].append(s.charAt(idx++));
                row++;
            }

            row -= 2;

            // Fill diagonally upward.
            while (row > 0 && idx < len) {
                rows[row].append(s.charAt(idx++));
                row--;
            }
        }

        // Concatenate all rows.
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < n; i++) {
            res.append(rows[i]);
        }

        return res.toString();
    }

    // Driver Code
    public static void main(String[] args)
    {
        String s = "GEEKSFORGEEKS";
        int n = 3;

        System.out.println("\"" + convert(s, n) + "\"");
    }
}
Python
def convert(s, n):
    # A single row produces the same string.
    if n <= 1:
        return s

    len_s = len(s)

    # Matrix used to store the Zig-Zag pattern.
    mat = [['\0' for _ in range(len_s)] for _ in range(n)]

    row = 0
    col = 0
    idx = 0

    while idx < len_s:
        # Fill downward.
        while row < n and idx < len_s:
            mat[row][col] = s[idx]
            idx += 1
            row += 1

        row -= 2
        col += 1

        # Fill diagonally upward.
        while row > 0 and idx < len_s:
            mat[row][col] = s[idx]
            idx += 1
            row -= 1
            col += 1

    # Concatenate all rows.
    res = ''.join(char for row in mat for char in row if char != '\0')
    return res


# Driver Code
if __name__ == "__main__":
    s = "GEEKSFORGEEKS"
    n = 3
    print("\"" + convert(s, n) + "\"")
C#
using System;
using System.Text;

public class GFG {
    static string Convert(string s, int n)
    {
        // A single row produces the same string.
        if (n <= 1)
            return s;

        int len = s.Length;

        // Store characters for each row.
        StringBuilder[] rows = new StringBuilder[n];
        for (int i = 0; i < n; i++) {
            rows[i] = new StringBuilder();
        }

        int row = 0;
        int idx = 0;

        while (idx < len) {
            // Fill downward.
            while (row < n && idx < len) {
                rows[row].Append(s[idx++]);
                row++;
            }

            row -= 2;

            // Fill diagonally upward.
            while (row > 0 && idx < len) {
                rows[row].Append(s[idx++]);
                row--;
            }
        }

        // Concatenate all rows.
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < n; i++) {
            res.Append(rows[i]);
        }

        return res.ToString();
    }

    // Driver Code
    public static void Main()
    {
        string s = "GEEKSFORGEEKS";
        int n = 3;

        Console.WriteLine("\"" + Convert(s, n) + "\"");
    }
}
JavaScript
function convert(s, n) {
    // A single row produces the same string.
    if (n <= 1)
        return s;

    let len = s.length;

    // Matrix used to store the Zig-Zag pattern.
    let mat = Array.from({ length: n }, () => Array(len).fill('\0'));

    let row = 0, col = 0;
    let idx = 0;

    while (idx < len) {
        // Fill downward.
        while (row < n && idx < len) {
            mat[row][col] = s[idx++];
            row++;
        }

        row -= 2;
        col++;

        // Fill diagonally upward.
        while (row > 0 && idx < len) {
            mat[row][col] = s[idx++];
            row--;
            col++;
        }
    }

    // Concatenate all rows.
    let res = '';
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < len; j++) {
            if (mat[i][j]!= '\0')
                res += mat[i][j];
        }
    }

    return res;
}

// Driver Code
let s = "GEEKSFORGEEKS";
let n = 3;
console.log(`\"${convert(s, n)}\"`);

Output
"GSGSEKFREKEOE"

[Expected Approach] Row-wise Zig-Zag Simulation - O(|s|) Time and O(|s|) Space

The idea is to simulate the Zig-Zag traversal row by row without constructing the actual pattern. We maintain a string for each row and place every character in its corresponding row while moving downward and upward. Finally, all row strings are concatenated to get the required Zig-Zag string.

Let us understand with example:
Input: s = "GEEKSFORGEEKS", n = 3
Initialize rows = {"", "", ""}, row = 0, and step = 1.
Traverse "GEEKSFORGEEKS" and place each character in the current row while moving down and up between rows.
After processing all characters, the rows become:

  • rows[0] = "GSGS"
  • rows[1] = "EKFREK"
  • rows[2] = "EOE"

Concatenate all row strings: "GSGS" + "EKFREK" + "EOE".
The final result is "GSGSEKFREKEOE".

C++
#include <iostream>
#include <vector>
using namespace std;

string convert(string &s, int n)
{

    // A single row produces the same string.
    if (n <= 1)
        return s;

    // Stores the characters belonging to each row
    // of the Zig-Zag pattern.
    vector<string> rows(n);

    int row = 0;

    // Direction of traversal:
    //  1  -> moving downward
    // -1  -> moving upward
    int step = 1;

    for (char ch : s)
    {

        // Place the current character in the current row.
        rows[row].push_back(ch);

        // Change direction when the topmost or
        // bottommost row is reached.
        if (row == 0)
            step = 1;
        else if (row == n - 1)
            step = -1;

        row += step;
    }

    // Concatenate all rows to form the final string.
    string res;
    for (const string &r : rows)
        res += r;

    return res;
}

// Driver Code
int main()
{
    string s = "GEEKSFORGEEKS";
    int n = 3;

    cout << "\"" << convert(s, n) << "\"" << endl;

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class GFG {
    // A single row produces the same string.
    public static String convert(String s, int n)
    {
        if (n <= 1)
            return s;

        // Stores the characters belonging to each row
        // of the Zig-Zag pattern.
        List<StringBuilder> rows = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            rows.add(new StringBuilder());
        }

        int row = 0;

        // Direction of traversal:
        //  1  -> moving downward
        // -1  -> moving upward
        int step = 1;

        for (char ch : s.toCharArray()) {

            // Place the current character in the current
            // row.
            rows.get(row).append(ch);

            // Change direction when the topmost or
            // bottommost row is reached.
            if (row == 0)
                step = 1;
            else if (row == n - 1)
                step = -1;

            row += step;
        }

        // Concatenate all rows to form the final string.
        StringBuilder res = new StringBuilder();
        for (StringBuilder r : rows) {
            res.append(r);
        }

        return res.toString();
    }

    // Driver Code
    public static void main(String[] args)
    {
        String s = "GEEKSFORGEEKS";
        int n = 3;

        System.out.println("\"" + convert(s, n) + "\"");
    }
}
Python
"""
A single row produces the same string.
"""


def convert(s, n):
    if n <= 1:
        return s

    # Stores the characters belonging to each row
    # of the Zig-Zag pattern.
    rows = ["" for _ in range(n)]

    row = 0

    # Direction of traversal:
    #  1  -> moving downward
    # -1  -> moving upward
    step = 1

    for ch in s:

        # Place the current character in the current row.
        rows[row] += ch

        # Change direction when the topmost or
        # bottommost row is reached.
        if row == 0:
            step = 1
        elif row == n - 1:
            step = -1

        row += step

    # Concatenate all rows to form the final string.
    res = ''.join(rows)

    return res


# Driver Code
# Driver Code
if __name__ == "__main__":
    s = "GEEKSFORGEEKS"
    n = 3
    print("\"" + convert(s, n) + "\"")
C#
using System;
using System.Text;

class GFG {
    static string convert(string s, int n)
    {
        // A single row produces the same string.
        if (n <= 1)
            return s;

        // Store characters for each row.
        StringBuilder[] rows = new StringBuilder[n];
        for (int i = 0; i < n; i++) {
            rows[i] = new StringBuilder();
        }

        int row = 0;

        // Direction of traversal:
        //  1 -> moving downward
        // -1 -> moving upward
        int step = 1;

        foreach(char ch in s)
        {
            // Place the character in the current row.
            rows[row].Append(ch);

            // Change direction at the topmost or bottommost
            // row.
            if (row == 0)
                step = 1;
            else if (row == n - 1)
                step = -1;

            row += step;
        }

        // Concatenate all rows.
        StringBuilder res = new StringBuilder();
        foreach(StringBuilder sb in rows)
        {
            res.Append(sb.ToString());
        }

        return res.ToString();
    }

    // Driver Code
    static void Main()
    {
        string s = "GEEKSFORGEEKS";
        int n = 3;

        Console.WriteLine("\"" + convert(s, n) + "\"");
    }
}
JavaScript
function convert(s, n) {
    // A single row produces the same string.
    if (n <= 1)
        return s;

    // Stores the characters belonging to each row
    // of the Zig-Zag pattern.
    let rows = Array.from({length: n}, () => '');

    let row = 0;

    // Direction of traversal:
    //  1  -> moving downward
    // -1  -> moving upward
    let step = 1;

    for (let ch of s) {

        // Place the current character in the current row.
        rows[row] += ch;

        // Change direction when the topmost or
        // bottommost row is reached.
        if (row === 0)
            step = 1;
        else if (row === n - 1)
            step = -1;

        row += step;
    }

    // Concatenate all rows to form the final string.
    return rows.join('');
}

// Driver Code
let s = 'GEEKSFORGEEKS';
let n = 3;

console.log('\"' + convert(s, n) + '\"');

Output
"GSGSEKFREKEOE"
Comment