![]() |
VOOZH | about |
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.
GSGSEKFREKEOE
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:
GSGSEKFREKEOE
Time Complexity: O(length)
Space Complexity: O(1)
Thanks to Sakshi Sachdeva for suggesting above solution.