Open In App

Decode the string encoded with the given algorithm

Last Updated : 31 May, 2021
Comments
Improve
Suggest changes
39 Likes
Like
Report

Given a decoded string str which was decoded with the following encoding algorithm: 
Write down the middle character of the string then delete it and repeat the process until there are no characters left. For example, “abba” will be encoded as “bbaa”
Note that the middle character is the first character of the two middle characters when the length of the string is even.
Examples:

Input: "ofrsgkeeeekgs"
Output: geeksforgeeks

Input: str = "bbaa"
Output: abba

Approach: It can be observed that while decoding the string, the first letter of the encoded string becomes the median of the decoded string. So first, write the very first character of the encoded string and remove it from the encoded string then start adding the first character of the encoded string first to the left and then to the right of the decoded string and do this task repeatedly till the encoded string becomes empty.
For example: 

Encoded String          Decoded String
ofrsgkeeeekgs           o
frsgkeeeekgs            fo
rsgkeeeekgs             for
sgkeeeekgs              sfor
gkeeeekgs               sforg
keeeekgs                ksforg
eeeekgs                 ksforge
eeekgs                  eksforge
eekgs                   eksforgee
ekgs                    eeksforgee
kgs                     eeksforgeek
gs                      geeksgorgeek
s                       geeksforgeeks                     

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to decode and print
// the original string
void decodeStr(string str, int len)
{
 
    // To store the decoded string
    char c[len] = "";
    int med, pos = 1, k;
 
    // Getting the mid element
    if (len % 2 == 1)
        med = len / 2;
    else
        med = len / 2 - 1;
 
    // Storing the first element of the
    // string at the median position
    c[med] = str[0];
 
    // If the length is even then store
    // the second element also
    if (len % 2 == 0)
        c[med + 1] = str[1];
 
    // k represents the number of characters
    // that are already stored in the c[]
    if (len & 1)
        k = 1;
    else
        k = 2;
 
    for (int i = k; i < len; i += 2) {
        c[med - pos] = str[i];
 
        // If string length is odd
        if (len % 2 == 1)
            c[med + pos] = str[i + 1];
 
        // If it is even
        else
            c[med + pos + 1] = str[i + 1];
        pos++;
    }
 
    // Print the decoded string
    for (int i = 0; i < len; i++)
        cout << c[i];
}
 
// Driver code
int main()
{
    string str = "ofrsgkeeeekgs";
    int len = str.length();
 
    decodeStr(str, len);
 
    return 0;
}


Java

Python3

C#

Javascript

Output: 

geeksforgeeks

 

The Complexity: O(n)
 



Next Article
Practice Tags :

Similar Reads