Concatenation of Zig-Zag String in N Rows
Last Updated :
21 Jun, 2022
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:
C++
// C++ code for the above approach
#include <bits/stdc++.h>
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
<script>
// JavaScript code for the above approach
// Function that Prints concatenation of
// all rows of str's Zig-Zag fashion
const printZigZagConcat = (str, n) => {
if (n == 1) {
document.write(`${str}<br/>`);
}
let res = "";
let arr = new Array(n).fill("");
let down = false;
let row = 0; // helps in building individual blocks of strings
for (let i = 0; i < str.length; i++) {
arr[row] += str[i];
if (row == n - 1) {
down = false;
}
if (row == 0) {
down = true;
}
if (!down)
row--;
else
row++;
}
for (let i = 0; i < n; i++) {
document.write(arr[i]);
}
}
// Driver Code
let str = "PAYPALISHIRING";
let N = 3;
printZigZagConcat(str, N);
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
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 concate
12 min read
Maximum Strings Concatenation Given an array of strings, where each string consists of lowercase characters from a to j. You need to find the maximum number of strings that can be concatenated together such that the resulting string can be made out of exactly k distinct characters. Example: Input: n = 4, str = [ "abc", "de", "fg
8 min read
Count ways to create string of size N with given restrictions Given a number N, the task is to count the number of ways to create a string of size N (only with capital alphabets) such that no vowel is between two consonants and the string does not start with the letter 'A' and does not end with the letter 'Z'. (Print the answer modulo 109 + 7). Examples: Input
15 min read
Print matrix in zig-zag fashion Given a matrix of 2D array of n rows and m columns. Print this matrix in ZIG-ZAG fashion as shown in figure. Example: Input: {{1, 2, 3}{4, 5, 6}{7, 8, 9}}Output: 1 2 4 7 5 3 6 8 9Input : [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]Output:: 1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16Thi
10 min read
Rearrange a Linked List in Zig-Zag fashion Given a linked list, rearrange it such that the converted list should be of the form a < b > c < d > e < f ⦠where a, b, c⦠are consecutive data nodes of the linked list. Examples: Input: 1->2->3->4 Output: 1->3->2->4 Explanation : 1 and 3 should come first before 2
15+ min read