Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Reverse a String With Spaces
00:00
5 left

Reverse a String With Spaces

EasyPython

Problem

Reverse a string while preserving the spaces.

Given a string s, reverse the order of all non-space characters while keeping each literal space character (' ') at its original index. Return the resulting string.

Function: def reverse_string(s):

Input: A string s.

Output: A string with non-space characters reversed and spaces unchanged.

Examples: "ab cd" becomes "dc ba"; "a b" becomes "b a".

Constraints: 0 <= len(s) <= 10^4; the input contains printable characters and spaces.

Constraints

  • 0 <= len(s) <= 10^4
  • Only the literal space character ' ' is preserved specially
  • All non-space characters may be reversed
  • Return a new string

Function Signature

def reverse_string(s):
Interviewer

Your question is Reverse a String With Spaces. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.