![]() |
VOOZH | about |
Given a string S and an integer R, the task is to encode the string by first filling each character in column wise manner from top to bottom in a matrix having R rows and then printing the matrix row-wise.
Examples:
Input: S = "abcdefgh", R = 3
Output: adgbehcf
Explanation: Matrix formed is:
a d g
b e h
c f
So when printed row wise it gives the encoded string as "adgbehcf"Input: S = "GeeksForGeeks", R = 5
Output: GFeeokerskGse
Explanation: Pattern formed is:
G f e
e o k
e r s
k G
s e
Approach: The approach is to use an array of string temp of size R. Traverse every character of string S and add it at the end of the string at i%R index of the array temp. Now traverse the temp array row-wise to get the encoded string.
Below is the implementation of the above approach.
GFeeokerskGse
Time Complexity: O(N), where N is the length of the string
Auxiliary Space: O(R), where R is the no of rows.