/151. Reverse Words in a String

151. Reverse Words in a String

Medium
Two Pointers55.7% acceptance

Given a string input_text consisting of English letters (upper-case and lower-case), digits, and spaces, reverse the order of the words. Words are defined as sequences of non-space characters separated by spaces. The output string should contain the words in reverse order, separated by a single space, with no leading or trailing spaces and no multiple spaces between words.

Example 1

Input: openai is awesome

Output: awesome is openai

Explanation: Multiple spaces are reduced to single spaces, and words are reversed.

Example 2

Input: python programming language

Output: language programming python

Explanation: Leading and trailing spaces are removed, words are reversed.

Example 3

Input: 123 456 789

Output: 789 456 123

Explanation: Digits are treated as words and reversed.

Constraints

  • 1 <= len(input_text) <= 10_000
  • input_text contains only English letters (upper-case and lower-case), digits, and spaces
  • There is at least one word in input_text
Python (current runtime)

Case 1

Input: 'data science is fun'

Expected: 'fun is science data'

Case 2

Input: ' machine learning '

Expected: 'learning machine'

Case 3

Input: 'a b c d e'

Expected: 'e d c b a'

Case 4

Input: 'singleword'

Expected: 'singleword'

Case 5

Input: ' hello world python '

Expected: 'python world hello'