The Wayback Machine - https://web.archive.org/web/20220105223209/https://www.geeksforgeeks.org/encode-given-string-by-inserting-in-matrix-column-wise-and-printing-it-row-wise/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 05 Jan, 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:

Resolution Days 2022 GeeksforGeeks

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 



 

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.

C++14




// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to encode the string
string printRowWise(string S, int R)
{
    vector<string> temp(R);
    string ans;
  
    for (int i = 0; i < S.length(); i++)
        temp[i % R].push_back(S[i]);
  
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < temp[i].size();
             j++)
            ans.push_back(temp[i][j]);
    }
    return ans;
}
  
// Driver code
int main()
{
    string S = "GeeksForGeeks";
    int R = 5;
    cout << printRowWise(S, R);
    return 0;
}
Output
GFeeokerskGse

Time Complexity: O(N) where N is the length of the string
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!