coding•DSA & Problem Solving•Strings & Two Pointers
Reverse Words in a String
Problem Statement
Given an input string `s`, reverse the order of the **words**.
A **word** is defined as a sequence of non-space characters. The words in `s` will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space. Note that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
### Constraints
- `1 <= s.length <= 10^4`
- `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`.
- There is at least one word in `s`.
### Input Format
A single line containing the string `s`.
### Output Format
Print the reversed string with words separated by single spaces.
Sample Cases
Example 1Sample Case
Input: the sky is blue
Output: blue is sky the
Example 2Sample Case
Input: hello world
Output: world hello
Example 3Sample Case
Input: t
Output: t
Example 4Sample Case
Input: th
Output: th
Constraints
Runtime Limit: 2000 ms per test batch
Memory Limit: 256 MB
Standard I/O stream reading
Official submissions are evaluated against hidden test cases on the server to verify time & memory complexity.