![]() |
VOOZH | about |
Given an encoded (or encrypted) string S of length N, an integer M. The task is to decrypt the encrypted string and print it. The encryption and decryption techniques are given as:
Encryption: The original string is placed in a Matrix of M rows and N/M columns, such that the first character of the Original text or string is placed on the top-left cell to the bottom-right manner. If last row is reached, then again go to the top row, and start from the next column.
For example: If string is "geeks", M = 2, then the string will be encrypted in below manner
👁 Image
Then traverse the matrix row wise and print the characters as they appear.
👁 Image
Therefore the above string will be encrypted as = "ges ek"
Decryption: Traverse the matrix diagonally in the same manner as it was encrypted and find the actual string.
👁 Image
Examples:
Input: "GSRE_ _ _E_ _K_ _ _EFGS_ _ _KOE" (Here '_' means a space), 4
👁 Image
Output: "GEEKS FOR GEEKS"
Explanation: See the image below for understanding the approach.
Here column number is 6.
So, the traversing starts from (0, 0) position, then goes upto the end of the row, means from (0, 0) --> (1, 1)-->(2, 2)-->(3, 3)-->(4, 4). T
hen get to the first row, and start from the next, means from (0, 1)-->(1, 2)-->(2, 3)->(3, 4) and continues upto it reaches to the end of the given string.Input: "GEEKSFORGEEKS", 1
👁 Image
Output: "GEEKSFORGEEKS"
Explanation: There is only one row. so the decoded string will be as same as the given encoded string.
Input: "abc de", 2
Output: "adbec"
Approach: First, find the number of columns. Then, start traversing. Follow the below steps to solve the problem:
For example, in the below picture, the X is a character, whose next diagonal character is XX, and the column number where X is present is 2, the next character row number is just one greater than the previous.
👁 Image
At last, print that string, and this will be the decoded string/desired string.
Below is the implementation of the above approach:
GEEKS FOR GEEKS
Time Complexity: O(M*(M/col)) which is near about O(length of the string)
Auxiliary Space: O(N)