Reverse a string but keep the spaces in place
Coding problemMediumAsked in: Infosys, Zupee
Given a string s, reverse the order of its non-space characters, but leave every space at exactly the position it had.
For "ab c" the space is at position 2. The other characters a, b, c in reverse are c, b, a; they fill the non-space positions from left to right, giving "cb a".
Examples
Example 1
Input: s = "ab c"
Output: "cb a"
Example 2
Input: s = "I am here"
Output: "e re hmaI"
Example 3
Input: s = " "
Output: " "
Only spaces: nothing moves.
Constraints
- The length of s is between 0 and 100,000
- Only the space character counts as a space
- s holds printable ASCII characters only
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.