Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Reverse Words In A String

Easy Acceptance 47.80% Points 20.00

Given a string s, reverse the order of the words in the string while keeping the individual words unchanged. Words are separated by spaces.

Note: The output string should have words separated by a single space, with no extra spaces at the beginning or end.

Examples
Example 1

Example 1

Input: s = "practice makes perfect"

Output: "perfect makes practice"

Explanation: After reversing the order of the words and trimming spaces, the result is "perfect makes practice".

Example 2

Example 2

Input: s = "here spaces multiple"

Output: "multiple spaces here"

Explanation: After reversing the words, the result is "multiple spaces here".

Hints
Hint 1
Expected Time Complexity: O(n)
Hint 2
Expected Space Complexity: O(n)
Constraints
  • 1 <= s.size() <= 10^6
  • String s contains only lowercase English alphabets and spaces.
Companies
Amazon Microsoft Adobe Goldman Sachs Cisco + 1 more
Topics
String
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions