Reverse the words

strings

Reverse the words

LinkedIn Python Interview Question

LinkedIn's messaging team is testing a playful feature that reads a sentence backwards, word by word.

Write a function reverse_words(sentence) that returns the words in reverse order, separated by single spaces. The sentence may have extra spaces at the start, at the end or between words.

Asked of

  • Data Analyst
  • Data Engineer
  • Data Scientist
  • ML Engineer
  • AI Engineer

Example 1

Input

sentence = "open to work"

Output

"work to open"

Example 2

Input

sentence = "  hello   world  "

Output

"world hello"

Explanation

In the first example, the three words come back in reverse order. In the second example, the extra spaces around and between the words are dropped, so only single spaces separate the reversed words.

Submit also runs 3 hidden test cases that check edge cases.