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


In this problem, we will encode the string by inserting it in the matrix in a column-wise manner and printing the string in a row-wise manner.

The naïve approach to solve the problem is to create a matrix, fill the matrix top-bottom manner, and print the string row-wise. The second solution is to use the vector to store the string and print each vector value individually. Here, we will learn both approaches to solve the problem.

Problem statement – We have given string str of length N. Also, we have given the positive integer rows. The task is to encode the string and print it in the output. To encode the string, we need to fill the string in the 2 dimensional array contains ‘row’ rows and print the string in a row-wise manner.

Sample examples

Input

str = "TutorialsPoint", rows = 4

Output

TrsnuiPttaooli

Explanation – We can fill the string in the matrix as shown below.

T r s n

u i P t

t a o

O l i

So, when we read the string row-wise, we get the TrsnuiPttaooli.

Input

str = "welcome", rows = 2

Output

wloeecm

Explanation – We can fill the string in the matrix as shown below.

w l o e

e c m

Input

str = ‘abcdefghijklmno’, row = 1

Output

‘abcdefghijklmno’

Explanation – As the row is 1, the encoded string is the same as the original string.

Approach 1

In this approach, we will decide the number of columns required based on the given string size and number of rows. After that, we will use the matrix of the desired dimension and fill the string in a top-bottom manner. To get the encoded string, we will traverse the matrix in a left-right manner.

Algorithm

Step 1 – Divide the string length by rows, and take its ceil value, representing total columns in the matrix.

Step 2 – Define the matrix of dimensions equal to rows and cols.

Step 3 – Initialize the k with 0, which is a string pointer.

Step 4 – Use two nested loops. The first loop makes iterations equal to the ‘cols’, and the second makes iterations equal to the ‘rows’.

Step 5 – If k is the string length, assign a kth character to the matrix[q][p]. Otherwise, assign space to the matrix.

Step 6 – Now, we need to print the encoded string. So, create a final_str string variable.

Step 7 – Use two nested loops to traverse the matrix row-wise. If matrix[p][q] doesn’t contain space, push the matrix[p][q] value to the final_Str.

Step 8 – Return the final_str variable value, representing the encoded string.

Example

#include <bits/stdc++.h>
using namespace std;

// Encoding the string
string getEncodedString(string str, int rows) {
    // finding required columns
    int cols = ceil((float)str.length() / rows);
    // Matrix of size rows*cols
    int matrix[rows][cols];
    // Inserting strings to the matrix in top to bottom manner
    int k = 0;
    for (int p = 0; p < cols; p++) {
        for (int q = 0; q < rows; q++) {
            // If all characters are traversed, add space to matrix
            if (k < str.length()) {
                matrix[q][p] = str[k++];
            } else {
                matrix[q][p] = ' ';
            }
        }
    }
    string final_str;
    // Getting the encoded string
    for (int p = 0; p < rows; p++) {
        for (int q = 0; q < cols; q++) {
            // If we find space, we need to ignore it
            if (matrix[p][q] != ' '){
                final_str.push_back(matrix[p][q]);
                
            }
        }
    }
    return final_str;
}
int main() {
    string str = "Tutorials Point";
    int rows = 2;
    cout << "The encoded string is " << getEncodedString(str, rows);
    return 0;
}

Output

The encoded string is TtrasPituoilon

Time complexity – O(N) as we traverse the string to insert it in the matrix.

Space complexity – O(N) as we store the string in the matrix.

Approach 2

This approach will create a string vector of size equal to the rows. We will traverse the string and append each character of the original string to the particular string of the vector so that we can encode the string properly.

Algorithm

Step 1 – Define a vector named ‘matrix’ of size equal to ‘rows’. Also, Define the ‘final_str’ string variable to store the encoded string.

Step 2 – Start traversing the string. Use the push_back() method to append the current character of the string at matrix[p % rows]. Here, we choose the row number based on the p-value.

Step 3 – Now, traverse the string vector to get the encoded string.

Step 4 – Use the nested loop to traverse each string character at index I in the vector. Take a character and append it to the fina_Str string.

Step 5 – At last, return the final_str string.

Example

#include <bits/stdc++.h>
using namespace std;

// Encoding the string
string getEncodedString(string str, int rows) {
    vector<string> matrix(rows);
    string final_str;
    // Inserting strings to the matrix
    for (int p = 0; p < str.length(); p++) {
        matrix[p % rows].push_back(str[p]);
    }
    // Getting the encoded string
    for (int p = 0; p < rows; p++) {
        for (int q = 0; q < matrix[p].size(); q++) {
            final_str.push_back(matrix[p][q]);
        }
    }
    return final_str;
}
int main() {
    string str = "TutorialsPoint";
    int rows = 4;
    cout << "The encoded string is " << getEncodedString(str, rows);
    return 0;
}

Output

The encoded string is TrsnuiPttaooli

Time complexity – O(N) as we traverse the string.

Space complexity – O(rows), as we create a string vector.

The second approach gives better performance in the time and space complexity manner. Furthermore, the second approach is more readable for programmers better understand the vector. The first approach is very beginner friendly.

Updated on: 24-Aug-2023

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements