Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Reverse Words With Single Spaces

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Reverse Words With Single Spaces. Start with the requirements on the right.

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.

Problem

The Zomato app may receive a search query containing leading spaces, trailing spaces, or multiple spaces between words. Given such a string, return a new string with the words in reverse order, separated by exactly one space, with no leading or trailing spaces.

A word is a maximal sequence of non-space characters. Only the space character is considered a separator.

Formal Specification

Implement reverse_words(s), where s is a string and the return value is a string. Preserve every word exactly, but reverse their order and normalize the separators.

Constraints

  • 0 <= len(s) <= 10^5
  • s contains only English letters and spaces
  • Words contain at least one non-space character
  • Return an empty string when no words are present

Function Signature

def reverse_words(s):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output