VOOZH about

URL: https://www.geeksforgeeks.org/dsa/encode-given-string-by-inserting-in-matrix-column-wise-and-printing-it-row-wise/

⇱ Encode given String by inserting in Matrix column-wise and printing it row-wise - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Encode given String by inserting in Matrix column-wise and printing it row-wise

Last Updated : 2 Aug, 2022

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.


Output
GFeeokerskGse

Time Complexity: O(N), where N is the length of the string
Auxiliary Space: O(R), where R is the no of rows.

Comment