JavaEasyStrings10 min
Reverse words in a sentence
Reverse the order of whitespace-delimited words. Normalize separators to one space and omit leading or trailing whitespace. Follow the stated ordering and edge-case conventions exactly. Interviewers use this task to probe boundary handling and collection selection.
Input
One line of text, possibly empty.
Output
Reverse the order of whitespace-delimited words. Normalize separators to one space and omit leading or trailing whitespace.
Constraints
0 <= line length <= 10000; ASCII text.
Example
Input
Java is fun
Output
fun is Java
Example 2 input
Output
—
This example exercises a further boundary or ordering case.
Public test cases (2)
Input
Java is fun
Expected output
fun is Java
Input
one two
Expected output
two one
Hints (2)
- Identify the state needed to avoid recomputing work for each element.
- Tokenize trimmed input and traverse the words from right to left.
Target complexity: time O(n) · space O(n)
