Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Reverse Words in a String

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

Your question is Reverse Words in a String. 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

Leidos systems may receive report text with inconsistent spacing before presenting it to an operator. Given a string, return the words in reverse order without reversing the characters inside any word.

Treat any sequence of spaces as a separator. The result must contain exactly one space between adjacent words and no leading or trailing spaces. If the input contains no words, return an empty string.

Formal Specification

Implement reverse_words(text), where text is a string and the return value is a string. A word is a maximal sequence of non-space characters. The relative character order within each word must remain unchanged, while the order of the words must be reversed.

Constraints

  • 0 <= len(text) <= 10^5
  • The input contains printable characters and spaces
  • A word contains one or more non-space characters
  • The output contains exactly one space between words

Function Signature

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