VOOZH about

URL: https://www.geeksforgeeks.org/dsa/concatenation-of-zig-zag-string-in-n-rows/

⇱ Concatenation of Zig-Zag String in N Rows - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Concatenation of Zig-Zag String in N Rows

Last Updated : 23 Jul, 2025

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.

Therefore, for given string str and an integer N, the task is to print the string formed by concatenating N rows when str is written in row-wise Zig-Zag fashion.

Example:

Input: str = "PAYPALISHIRING", N = 3
Output: PAHNAPLSIIGYIR

Input: str = "ABCDEFGH", N = 2
Output: ACEGBDFH
Explanation: The input string can be written in Zig-Zag fashion in 2 rows as follows:
A   C    E   G    
   B   D   F   H
Hence, upon reading the above pattern row-wise, the output string is "ACEGBDFH"

Approach: The given problem is an implementation based problem that can be solved by following the below steps

  • Create an array of N strings, arr[N].
  • Initialize direction as "down" and row as 0. The direction indicates whether the current pointer is moving up or down in rows.
  • Traverse the input string, do the following for every character.
    • Append the current character to the string representing the current row.
    • If row number is N - 1, then change direction to 'up'
    • If row number is 0, then change direction to 'down'
    • If direction is 'down', do row++.  Else do row--.
  • One by one print all strings of arr[].

Below is the implementation of the above approach:


Output
PAHNAPLSIIGYIR

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment
Article Tags: