Decode a median string to the original string
Given a string s written in median form, change it back to the original string. The median letter in a string is the letter that is in the middle of the string. If the string’s length is even, the median letter is the left of the two middle letters. The given string is formed by writing down the median letter of the word, then deleting it and repeating the process until there are no letters left.
Input: eekgs Output: geeks Explanation: in the original string “geeks” can be written in median form by picking up e first then, again e, then k then g and at the end s. As these are the median when the median letter is picked and deleted. Input: abc Output: bac Explanation: median of bac is a, then median of bc is b, then median of c is c.
To find the answer we can iterate through the given encoded string from left to right and add each letter in the answer string, one letter to the beginning, next letter to the end, next letter to begin, and so on. If n is even then the first letter must be added to the beginning and the second letter to the end. In the other case, the first letter to the end, second to the beginning. We need to make it until we do not add all letters from the given string.
Note: For strings with even length, when we add the first character to begin and the second character to the end then the remaining string will always be of even length. The same is true for strings with odd lengths.
Given below is the implementation of the above approach
Time complexity: O(n)
This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.