Mirrored Reversal of String

Moderate
0/80
0 upvote
Asked in company
Euler Motors

Problem statement

You are given a string s that contains words separated by one or more spaces. Your task is to perform a "mirrored reversal" on the string.


A mirrored reversal consists of two steps:

1) Reverse the order of the words in the string.


2) Reverse the characters within each of those words.


Crucially, the original pattern of whitespace (the number of spaces between words, and any leading/trailing spaces) must be preserved and redistributed between the newly ordered words.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
A single line containing the string s.


Output Format:
Print the modified string on a single line.
Sample Input 1:
hi myself john


Sample Output 1:
nhoj flesym ih


Explanation for Sample 1:
1.  The words are `["hi", "myself", "john"]`.
2.  The separators are `[" ", " "]`.
3.  Reverse the order of words: `["john", "myself", "hi"]`.
4.  Reverse the characters in each word: `["nhoj", "flesym", "ih"]`.
5.  Reconstruct the string with the original separators: `nhoj` + ` ` + `flesym` + ` ` + `ih`.


Sample Input 2:
  a b  c  


Sample Output 2:
  c b  a  


Explanation for Sample 2:
1.  Words: `["a", "b", "c"]`. Separators: `["      ", " ", "  "]` (leading, between, trailing).
2.  Reverse words: `["c", "b", "a"]`.
3.  Reverse characters: `["c", "b", "a"]`.
4.  Reconstruct: `      ` + `c` + ` ` + `b` + `  ` + `a`.


Expected Time Complexity:
The expected time complexity is O(N), where N is the length of the string.
Approaches (1)
Mirrored Reversal of String
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Mirrored Reversal of String
Full screen
Console