Print Concatenation of Zig-Zag String in ‘n’ Rows
Given a string and number of rows ‘n’. Print the string formed by concatenating n rows when input string is written in row-wise Zig-Zag fashion.
Examples:
Input: str = "ABCDEFGH"
n = 2
Output: "ACEGBDFH"
Explanation: Let us write input string in Zig-Zag fashion
in 2 rows.
A C E G
B D F H
Now concatenate the two rows and ignore spaces
in every row. We get "ACEGBDFH"
Input: str = "GEEKSFORGEEKS"
n = 3
Output: GSGSEKFREKEOE
Explanation: Let us write input string in Zig-Zag fashion
in 3 rows.
G S G S
E K F R E K
E O E
Now concatenate the two rows and ignore spaces
in every row. We get "GSGSEKFREKEOE"
The idea is to traverse the input string. Every character has to go to one of the rows. One by one add all characters to different rows. Below is algorithm:
1) Create an array of n strings, arr[n]
2) Initialize direction as "down" and row as 0. The
direction indicates whether we need to move up or
down in rows.
3) Traverse the input string, do following for every
character.
a) Append current character to string of current row.
b) If row number is n-1, then change direction to 'up'
c) If row number is 0, then change direction to 'down'
d) If direction is 'down', do row++. Else do row--.
4) One by one print all strings of arr[].
Below is the implementation of above idea.
C++
#include<bits/stdc++.h>
using namespace std;
void printZigZagConcat(string str, int n)
{
if (n == 1)
{
cout << str;
return ;
}
int len = str.length();
string arr[n];
int row = 0;
bool down;
for ( int i = 0; i < len; ++i)
{
arr[row].push_back(str[i]);
if (row == n-1)
down = false ;
else if (row == 0)
down = true ;
(down)? (row++): (row--);
}
for ( int i = 0; i < n; ++i)
cout << arr[i];
}
int main()
{
string str = "GEEKSFORGEEKS" ;
int n = 3;
printZigZagConcat(str, n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
static void printZigZagConcat(String str,
int n)
{
if (n == 1 )
{
System.out.print(str);
return ;
}
char [] str1 = str.toCharArray();
int len = str.length();
String[] arr = new String[n];
Arrays.fill(arr, "" );
int row = 0 ;
boolean down = true ;
for ( int i = 0 ; i < len; ++i)
{
arr[row] += (str1[i]);
if (row == n - 1 )
{
down = false ;
}
else 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)
{
String str = "GEEKSFORGEEKS" ;
int n = 3 ;
printZigZagConcat(str, n);
}
}
|
Python3
def printZigZagConcat( str , n):
if n = = 1 :
print ( str )
return
l = len ( str )
arr = ["" for x in range (l)]
row = 0
for i in range (l):
arr[row] + = str [i]
if row = = n - 1 :
down = False
elif row = = 0 :
down = True
if down:
row + = 1
else :
row - = 1
for i in range (n):
print (arr[i], end = "")
str = "GEEKSFORGEEKS"
n = 3
printZigZagConcat( str , n)
|
C#
using System;
class GFG
{
static void printZigZagConcat( string str,
int n)
{
if (n == 1)
{
Console.Write(str);
return ;
}
char [] str1 = str.ToCharArray();
int len = str.Length;
string []arr = new string [n];
int row = 0;
bool down = true ;
for ( int i = 0; i < len; ++i)
{
arr[row] += (str1[i]);
if (row == n - 1)
down = false ;
else if (row == 0)
down = true ;
if (down)
row++;
else
row--;
}
for ( int i = 0; i < n; ++i)
Console.Write(arr[i]);
}
public static void Main()
{
String str = "GEEKSFORGEEKS" ;
int n = 3;
printZigZagConcat(str, n);
}
}
|
Javascript
<script>
function printZigZagConcat(str,n)
{
if (n == 1)
{
document.write(str);
return ;
}
let str1 = str.split( "" );
let len = str.length;
let arr = new Array(n);
for (let i=0;i<n;i++)
{
arr[i]= "" ;
}
let row = 0;
let down = true ;
for (let i = 0; i < len; ++i)
{
arr[row] += (str1[i]);
if (row == n - 1)
{
down = false ;
}
else if (row == 0)
{
down = true ;
}
if (down)
{
row++;
}
else
{
row--;
}
}
for (let i = 0; i < n; ++i)
{
document.write(arr[i]);
}
}
let str = "GEEKSFORGEEKS" ;
let n = 3;
printZigZagConcat(str, n);
</script>
|
Time Complexity: O(len) where len is length of input string.
Auxiliary Space: O(len)
Thanks to Gaurav Ahirwar for suggesting above solution.
Another Approach:
If we assume that we are iterating through imaginary matrix of row count n one by one and printing chars
for first and last row, index will increment by a value of i+= 2*(n-1)
for middle rows, if we are going in upward direction, index will increment as i+= 2*(n-rowNum-1), and for downward direction, index will increment as 2*rowNum. Following is the working implementation. in JAVA
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
string zigZagConcat(string s, int n)
{
if (n <= 1)
{
return s;
}
string result = "" ;
for ( int rowNum = 0; rowNum < n; rowNum++)
{
int i = rowNum;
bool up = true ;
while (i < s.length())
{
result += s[i];
if (rowNum == 0 || rowNum == n - 1)
{
i += (2 * n - 2);
}
else
{
if (up)
{
i += (2 * (n - rowNum) - 2);
}
else
{
i += rowNum * 2;
}
up ^= true ;
}
}
}
return result;
}
int main()
{
string str = "GEEKSFORGEEKS" ;
int n = 3;
cout<< zigZagConcat(str, n);
}
|
Java
import java.lang.*;
class Solution
{
private static String zigZagConcat(
String s, int n)
{
if (n <= 1 )
{
return s;
}
StringBuilder result = new
StringBuilder();
for ( int rowNum = 0 ; rowNum < n; rowNum++)
{
int i = rowNum;
boolean up = true ;
while (i < s.length())
{
result = result.append(s.charAt(i));
if (rowNum == 0 || rowNum == n - 1 )
{
i += ( 2 * n - 2 );
}
else
{
if (up)
{
i += ( 2 * (n - rowNum) - 2 );
}
else
{
i += rowNum * 2 ;
}
up ^= true ;
}
}
}
return result.toString();
}
public static void main(String[] args)
{
String str = "GEEKSFORGEEKS" ;
int n = 3 ;
System.out.println(zigZagConcat(str, n));
}
}
|
Python3
def zigZagConcat(s, n):
if (n < = 1 ):
return s
result = ""
for rowNum in range (n):
i = rowNum
up = True
while (i < len (s)):
result + = s[i]
if (rowNum = = 0 or rowNum = = n - 1 ):
i + = ( 2 * n - 2 )
else :
if (up):
i + = ( 2 * (n - rowNum) - 2 )
else :
i + = rowNum * 2
up ^ = True
return result
str = "GEEKSFORGEEKS"
n = 3
print (zigZagConcat( str , n))
|
C#
using System;
public class GFG{
static string zigZagConcat( string s, int n)
{
if (n <= 1)
{
return s;
}
string result= "" ;
for ( int rowNum = 0; rowNum < n; rowNum++)
{
int i = rowNum;
bool up = true ;
while (i < s.Length)
{
result += s[i];
if (rowNum == 0 || rowNum == n - 1)
{
i += (2 * n - 2);
}
else
{
if (up)
{
i += (2 * (n - rowNum) - 2);
}
else
{
i += rowNum * 2;
}
up ^= true ;
}
}
}
return result;
}
static public void Main (){
string str = "GEEKSFORGEEKS" ;
int n = 3;
Console.WriteLine(zigZagConcat(str, n));
}
}
|
Javascript
<script>
function zigZagConcat(s,n)
{
if (n <= 1)
{
return s;
}
let result = [];
for (let rowNum = 0; rowNum < n; rowNum++)
{
let i = rowNum;
let up = true ;
while (i < s.length)
{
result.push(s[i]);
if (rowNum == 0 || rowNum == n - 1)
{
i += (2 * n - 2);
}
else
{
if (up)
{
i += (2 * (n - rowNum) - 2);
}
else
{
i += rowNum * 2;
}
up ^= true ;
}
}
}
return result.join( "" );
}
let str = "GEEKSFORGEEKS" ;
let n = 3;
document.write(zigZagConcat(str, n));
</script>
|
Time Complexity: O(length)
Space Complexity: O(1)
Thanks to Sakshi Sachdeva for suggesting above solution.
Last Updated :
01 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...