Backlog·queued
Reverse Words in a String
DifficultyMedium
PatternTwo Pointers
TrackDSA
tl;dr
Given a sentence, reverse the order of its words without affecting the order of letters within a given word.
full write-up
Constraints
- Sentence contains English uppercase and lowercase letters, digits, and spaces.
- 1 ≤
sentence.length≤ 10⁴ - The order of the letters within a word is not to be reversed.
Note: The input string may contain leading or trailing spaces or multiple spaces between words. The returned string, however, should only have a single space separating each word. Do not include any extra spaces.
Examples
Example 1
Input String: "Hello Friend"
Reversed String: "Friend Hello"
Example 2
Input String: "Welcome to Educative"
Reversed String: "Educative to Welcome"
Example 3
Input String: "Hurray 3 2 1"
Reversed String: "1 2 3 Hurray"