L1 · FoundationsText basics~2 min · 4 tests

Reverse the Words in a Sentence

Reverse the order of words in a sentence with split() and join(), collapsing extra spaces. A frequent Python interview question with live tests.

The problem

Return the words of sentence in reverse order, separated by single spaces. Extra spaces anywhere are dropped.

"I love Python" → "Python love I".

Examples

  1. Example 1

    Input

    reverse_words('I love Python')

    Expected output

    'Python love I'
  2. Example 2

    Input

    reverse_words('  hello   world  ')

    Expected output

    'world hello'

+ 2 hidden tests on Submit.

Edge cases to ask about

  • Extra spaces
  • Single word
  • Empty string

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · reverse_words
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    split → reverse → joinO(n)O(n)split() with no argument collapses whitespace.
    Walkthrough of the optimal approach (try it yourself first)

    sentence.split() (no argument) splits on any run of whitespace and drops leading/trailing spaces. Reverse the list and " ".join it back. split(" ") would keep empty strings for the extra spaces — a common slip.

    Complexity: O(n) time, O(n) space. Splitting and joining each touch every character once.

    Reveal the reference solution
    def reverse_words(sentence):
        return " ".join(reversed(sentence.split()))

    Follow-ups interviewers ask

    • Reverse each word but keep word order.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Reverse the Words in a Sentence in Python?

    The optimal solution runs in O(n) time and O(n) auxiliary space. Splitting and joining each touch every character once.

    What follow-up questions do interviewers ask about Reverse the Words in a Sentence?

    Reverse each word but keep word order.