Open in App
Not now

Concatenation of Zig-Zag String in N Rows

• Difficulty Level : Medium
• Last Updated : 21 Jun, 2022

The stringPAYPALISHIRING” 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:

C++

 `// C++ code for the above approach` `#include ` `using` `namespace` `std;`   `// Function that Prints concatenation of` `// all rows of str's Zig-Zag fashion` `void` `printZigZagConcat(string str, ``int` `n)` `{` `    ``if` `(n == 1)` `    ``{` `        ``cout << str << endl;` `    ``}` `    ``string res = ``""``;` `    ``string arr[n] = {``""``};` `    ``bool` `down;` `    ``int` `row = 0; ``// helps in building individual blocks of strings`   `    ``for` `(``int` `i = 0; i < str.size(); i++)` `    ``{` `        ``arr[row].push_back(str[i]);` `        ``if` `(row == n - 1)` `        ``{` `            ``down = ``false``;` `        ``}` `        ``if` `(row == 0)` `        ``{` `            ``down = ``true``;` `        ``}` `        ``if` `(!down)` `            ``row--;` `        ``else` `            ``row++;` `    ``}`   `    ``for` `(``int` `i = 0; i < n; i++)` `    ``{` `        ``cout << arr[i];` `    ``}` `}`   `int` `main()` `{` `    ``// Driver Code` `    ``string str = ``"PAYPALISHIRING"``;` `    ``int` `N = 3;` `    ``printZigZagConcat(str, N);` `    ``return` `0;` `}`   `// This code is contributed by Potta Lokesh`

Java

 `// Java code for the above approach` `import` `java.util.*;`   `class` `GFG {`   `  ``// Function that Prints concatenation of` `  ``// all rows of str's Zig-Zag fashion` `  ``static` `void` `printZigZagConcat(String str, ``int` `n)` `  ``{` `    ``if` `(n == ``1``) {` `      ``System.out.print(str + ``"\n"``);` `    ``}` `    ``String res = ``""``;` `    ``String[] arr = ``new` `String[n];` `    ``for` `(``int` `i = ``0``; i < n; i++)` `      ``arr[i] = ``""``;` `    ``boolean` `down = ``false``;` `    ``int` `row = ``0``; ``// helps in building individual blocks` `    ``// of Strings`   `    ``for` `(``int` `i = ``0``; i < str.length(); i++) {` `      ``if` `(row >= ``0``)` `        ``arr[row] += (str.charAt(i));` `      ``if` `(row == n - ``1``) {` `        ``down = ``false``;` `      ``}` `      ``if` `(row == ``0``) {` `        ``down = ``true``;` `      ``}` `      ``if` `(!down)` `        ``row--;` `      ``else` `        ``row++;` `    ``}`   `    ``for` `(``int` `i = ``0``; i < n; i++) {` `      ``System.out.print(arr[i]);` `    ``}` `  ``}`   `  ``public` `static` `void` `main(String[] args)` `  ``{` `    ``// Driver Code` `    ``String str = ``"PAYPALISHIRING"``;` `    ``int` `N = ``3``;` `    ``printZigZagConcat(str, N);` `  ``}` `}`   `// This code is contributed by umadevi9616`

Python3

 `# Python 3 program of the above approach`   `# Function that Prints concatenation of` `# all rows of str's Zig-Zag fashion` `def` `printZigZagConcat(``str``, n):`   `    ``# Corner Case (Only one row)` `    ``if` `n ``=``=` `1``:` `        ``print``(``str``)` `        ``return`   `    ``# Find length of string` `    ``l ``=` `len``(``str``)`   `    ``# Create an array of` `    ``# strings for all n rows` `    ``arr ``=` `["" ``for` `x ``in` `range``(l)]`   `    ``# Initialize index for` `    ``# array of strings arr[]` `    ``row ``=` `0`   `    ``# Traverse through` `    ``# given string` `    ``for` `i ``in` `range``(l):`   `        ``# append current character` `        ``# to current row` `        ``arr[row] ``+``=` `str``[i]`   `        ``# If last row is reached,` `        ``# change direction to 'up'` `        ``if` `row ``=``=` `n ``-` `1``:` `            ``down ``=` `False`   `        ``# If 1st row is reached,` `        ``# change direction to 'down'` `        ``elif` `row ``=``=` `0``:` `            ``down ``=` `True`   `        ``# If direction is down,` `        ``# increment, else decrement` `        ``if` `down:` `            ``row ``+``=` `1` `        ``else``:` `            ``row ``-``=` `1`   `    ``# Print concatenation` `    ``# of all rows` `    ``for` `i ``in` `range``(n):` `        ``print``(arr[i], end``=``"")`     `# Driver Code` `str` `=` `"PAYPALISHIRING"` `N ``=` `3` `printZigZagConcat(``str``, N)`

C#

 `// C# program to implement above approach` `using` `System;` `using` `System.Collections;` `using` `System.Collections.Generic;`   `class` `GFG` `{`   `  ``// Function that Prints concatenation of` `  ``// all rows of str's Zig-Zag fashion` `  ``static` `void` `printZigZagConcat(String str, ``int` `n)` `  ``{` `    ``if` `(n == 1) {` `      ``Console.WriteLine(str);` `    ``}`   `    ``String[] arr = ``new` `String[n];` `    ``for` `(``int` `i = 0 ; i < n ; i++)` `      ``arr[i] = ``""``;`   `    ``bool` `down = ``false``;` `    ``int` `row = 0; ``// helps in building individual blocks` `    ``// of Strings`   `    ``for` `(``int` `i = 0 ; i < str.Length ; i++) {` `      ``if` `(row >= 0)` `        ``arr[row] += (str[i]);` `      ``if` `(row == n - 1) {` `        ``down = ``false``;` `      ``}` `      ``if` `(row == 0) {` `        ``down = ``true``;` `      ``}` `      ``if` `(!down)` `        ``row--;` `      ``else` `        ``row++;` `    ``}`   `    ``for` `(``int` `i = 0; i < n; i++) {` `      ``Console.Write(arr[i]);` `    ``}` `  ``}`     `  ``// Driver code` `  ``public` `static` `void` `Main(``string``[] args){`   `    ``// Driver Code` `    ``String str = ``"PAYPALISHIRING"``;` `    ``int` `N = 3;` `    ``printZigZagConcat(str, N);`   `  ``}` `}`   `// This code is contributed by subhamgoyal2014.`

Javascript

 ``

Output

`PAHNAPLSIIGYIR`

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

My Personal Notes arrow_drop_up
Related Articles