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.
Examples:
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
C++
< div id= "highlighter_83851" class = "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class = "code" >< div class = "container" >< div class = "line number1 index0 alt2" ><code class = "comments" >
|
Java
Python3
C#
Javascript
<script>
function decodeMedianString( s) {
var l = s.length;
var s1 = "" ;
var isEven = (l % 2 == 0) ? true : false ;
for (i = 0; i < l; i += 2) {
if (isEven) {
s1 = s.charAt(i) + s1;
s1 += s.charAt(i + 1);
} else {
if (l - i > 1) {
s1 += s.charAt(i);
s1 = s.charAt(i + 1) + s1;
} else {
s1 += s.charAt(i);
}
}
}
return s1;
}
var s = "eekgs" ;
document.write(decodeMedianString(s));
</script>
|
Time Complexity: O(N), as we are using a loop to traverse N times.
Auxiliary Space: O(1), as we are not using any extra space.
Last Updated :
18 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...