Reverse Words in a String
Java coding interview problem for String Coding: Reverse Words in a String.
Reversing words in a string is one of the most common Java String interview questions.
Although the problem appears simple, it evaluates several important programming concepts, including:
- String Manipulation
- String Splitting
- Arrays
- StringBuilder
- StringTokenizer
- Two Pointers
- Stack
- Java Streams
- Time Complexity
Interviewers often ask several variations such as:
- Reverse the order of words.
- Reverse every individual word.
- Reverse words without using
split(). - Preserve multiple spaces.
- Reverse words in-place.
Understanding multiple approaches prepares you for all these interview variations.
Problem Statement
Given a sentence, reverse the order of the words while preserving each word itself.
Return the reversed sentence.
Example 1
Input
Java is awesome
Output
awesome is Java
Example 2
Input
Hello World
Output
World Hello
Example 3
Input
I love programming
Output
programming love I
Example 4
Input
Welcome to CodeWithVenu
Output
CodeWithVenu to Welcome
What is Reverse Words in a String?
The goal is to reverse the position of words, not the characters inside each word.
Example
Input
Java Spring Boot
Output
Boot Spring Java
Notice
The characters inside every word remain unchanged.
Another Example
Input
I Love Java
Output
Java Love I
Why is this Question Asked in Interviews?
Interviewers use this question to evaluate whether candidates understand:
- String Traversal
- Arrays
- StringBuilder
- Loops
- Stack
- Two Pointer Technique
- Time Complexity
- Space Complexity
This problem also forms the foundation for advanced string manipulation questions.
Examples include:
- Reverse Each Word
- Reverse Sentence Without split()
- Reverse Characters
- Reverse Words Preserving Spaces
- Reverse Words In-place
Real-World Applications
Reversing words has many real-world applications.
Search Engines
Search engines process user queries by rearranging words during indexing.
Text Editors
Editors support reversing or rearranging text for formatting.
Natural Language Processing (NLP)
Word manipulation is commonly used during sentence preprocessing.
Chat Applications
Messaging applications transform and format user input.
Data Processing Pipelines
Text transformation is frequently performed before analytics.
Understanding Words vs Characters
Many beginners confuse these two interview questions.
Reverse Characters
Input
Java
Output
avaJ
Characters are reversed.
Reverse Words
Input
Java Spring Boot
Output
Boot Spring Java
Words are reversed.
Characters inside each word remain unchanged.
Reverse Entire String vs Reverse Words
These are different interview questions.
Reverse Entire String
Input
Java Spring
Output
gnirpS avaJ
Reverse Word Order
Input
Java Spring
Output
Spring Java
Reverse Every Word
Input
Java Spring
Output
avaJ gnirpS
Interviewers often ask all three variations.
Mathematical Concept
Suppose
A B C D
Index
0 1 2 3
Reverse Order
3 2 1 0
Output
D C B A
Visual Representation
Input
Java is awesome
Split
+------+----+---------+
| Java | is | awesome |
+------+----+---------+
Reverse Traversal
awesome
↓
is
↓
Java
Output
awesome is Java
Dry Run
Input
Java is awesome
Split
["Java", "is", "awesome"]
Start from the last word.
Iteration 1
awesome
Result
awesome
Iteration 2
is
Result
awesome is
Iteration 3
Java
Result
awesome is Java
Final Output
awesome is Java
Approach 1 — Using split() + Reverse Traversal (Recommended)
This is the most common interview solution.
The idea is simple:
- Split the sentence into words.
- Traverse the array in reverse order.
- Append every word using
StringBuilder.
Algorithm
- Split the string using spaces.
- Create a
StringBuilder. - Traverse from the last word to the first.
- Append every word.
- Return the result.
Java Program
public class ReverseWords {
public static String reverseWords(String input) {
String[] words = input.split(" ");
StringBuilder result = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
result.append(words[i]);
if (i != 0) {
result.append(" ");
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(reverseWords("Java is awesome"));
System.out.println(reverseWords("Welcome to CodeWithVenu"));
}
}
Output
awesome is Java
CodeWithVenu to Welcome
Step-by-Step Code Explanation
Split the sentence.
String[] words = input.split(" ");
Example
Java is awesome
↓
["Java","is","awesome"]
Create a StringBuilder.
StringBuilder result = new StringBuilder();
Traverse backwards.
for (int i = words.length - 1; i >= 0; i--)
Append every word.
result.append(words[i]);
Append a space except after the last word.
if (i != 0) {
result.append(" ");
}
Return the final string.
return result.toString();
Dry Run of split() Approach
Input
Hello Java World
Split
["Hello","Java","World"]
| Iteration | Word | Result |
|---|---|---|
| 1 | World | World |
| 2 | Java | World Java |
| 3 | Hello | World Java Hello |
Output
World Java Hello
Advantages
- Very easy to understand.
- Most common interview solution.
- Excellent readability.
- Easy to implement.
- Uses built-in Java APIs.
Drawbacks
- Creates an additional array.
- Extra memory due to
split(). - Does not preserve multiple consecutive spaces by default.
Approach 2 — Using StringTokenizer
StringTokenizer is another classic Java utility for splitting strings into words.
Instead of creating an array directly, it extracts one token (word) at a time.
These words are then stored in a list and traversed in reverse order.
Although less common in modern Java, interviewers may ask about it to evaluate your knowledge of older Java APIs.
Algorithm
- Create a
StringTokenizer. - Read each token.
- Store the words in a list.
- Traverse the list in reverse order.
- Build the final string.
Java Program
import java.util.ArrayList;
import java.util.StringTokenizer;
public class ReverseWordsTokenizer {
public static String reverseWords(String input) {
StringTokenizer tokenizer = new StringTokenizer(input);
ArrayList<String> words = new ArrayList<>();
while (tokenizer.hasMoreTokens()) {
words.add(tokenizer.nextToken());
}
StringBuilder result = new StringBuilder();
for (int i = words.size() - 1; i >= 0; i--) {
result.append(words.get(i));
if (i != 0) {
result.append(" ");
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(reverseWords("Java Spring Boot"));
}
}
Output
Boot Spring Java
Step-by-Step Code Explanation
Create the tokenizer.
StringTokenizer tokenizer = new StringTokenizer(input);
Extract every word.
tokenizer.nextToken();
Store the words.
words.add(...);
Traverse from the end.
for (int i = words.size() - 1; i >= 0; i--)
Append each word.
result.append(words.get(i));
Return the result.
return result.toString();
Time & Space Complexity
| Approach | Time | Extra Space |
|---|---|---|
| split() + Reverse Traversal | O(n) | O(n) |
| StringTokenizer | O(n) | O(n) |
Where:
- n = length of the input string.
Both approaches scan the string once and require additional storage for the extracted words.
Comparison of Approaches
| Feature | split() | StringTokenizer |
|---|---|---|
| Easy to Learn | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Interview Friendly | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Modern Java | ⭐⭐⭐⭐⭐ | ⭐⭐ |
| Performance | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Uses Built-in API | ✅ | ✅ |
Advantages
- Both solutions are simple and easy to explain.
split()is the preferred modern Java approach.StringTokenizerdemonstrates knowledge of legacy Java APIs.- Both preserve the characters inside each word while reversing the word order.
Drawbacks
- Both approaches allocate additional memory for storing words.
- Neither approach performs an in-place reversal.
- Extra handling is required to preserve multiple consecutive spaces.
In Part 2, we'll cover:
- Approach 3 – Using Two Pointers
- Approach 4 – Using Stack
- Approach 5 – Using Java Streams (Java 8+)
- Reverse Words While Preserving Multiple Spaces
- Reverse Each Word Instead of Word Order
- Unicode Considerations
- Comparison of All Approaches
- Common Interview Mistakes
- Edge Cases
- Interview Follow-up Questions
- Related Problems
- Key Takeaways
- Frequently Asked Interview Questions
- Interview Tips
Approach 3 — Using Two Pointers (Without split())
Some interviewers ask:
Can you reverse words without using
split()?
A common solution is the Two Pointer Technique.
The idea is:
- Start from the end of the string.
- Locate each word using two pointers.
- Append the words one by one.
This avoids creating an array using split().
Algorithm
- Start from the last character.
- Skip trailing spaces.
- Find the beginning of the current word.
- Append the word.
- Repeat until the beginning of the string.
Java Program
public class ReverseWordsTwoPointers {
public static String reverseWords(String input) {
StringBuilder result = new StringBuilder();
int end = input.length() - 1;
while (end >= 0) {
while (end >= 0 && input.charAt(end) == ' ') {
end--;
}
if (end < 0) {
break;
}
int start = end;
while (start >= 0 && input.charAt(start) != ' ') {
start--;
}
result.append(input, start + 1, end + 1);
result.append(" ");
end = start - 1;
}
return result.toString().trim();
}
public static void main(String[] args) {
System.out.println(reverseWords("Java is awesome"));
}
}
Output
awesome is Java
Advantages
- Does not use
split(). - Efficient traversal.
- Frequently asked in interviews.
Drawbacks
- Slightly harder to understand.
- More pointer manipulation.
Approach 4 — Using Stack
A stack naturally reverses the order of elements because it follows the Last In, First Out (LIFO) principle.
Example
Input
Java Spring Boot
Push
Java
↓
Spring
↓
Boot
Pop
Boot
↓
Spring
↓
Java
Algorithm
- Split the sentence.
- Push every word into a stack.
- Pop words one by one.
- Build the final sentence.
Java Program
import java.util.Stack;
public class ReverseWordsStack {
public static String reverseWords(String input) {
String[] words = input.split(" ");
Stack<String> stack = new Stack<>();
for (String word : words) {
stack.push(word);
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.append(stack.pop());
if (!stack.isEmpty()) {
result.append(" ");
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(reverseWords("Hello Java World"));
}
}
Output
World Java Hello
Advantages
- Very intuitive.
- Demonstrates Stack usage.
- Easy to explain.
Drawbacks
- Requires extra memory.
- Slightly slower than direct traversal.
Approach 5 — Using Java Streams (Java 8+)
Java Streams provide a concise and modern solution.
Java Program
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class ReverseWordsStreams {
public static String reverseWords(String input) {
List<String> words =
Arrays.asList(input.split(" "));
Collections.reverse(words);
return words.stream()
.collect(Collectors.joining(" "));
}
public static void main(String[] args) {
System.out.println(
reverseWords("Welcome to CodeWithVenu"));
}
}
Output
CodeWithVenu to Welcome
Advantages
- Modern Java.
- Concise implementation.
- Easy to read.
Drawbacks
- Stream overhead.
- Not usually preferred in coding interviews.
Reverse Words While Preserving Multiple Spaces
Sometimes interviewers ask:
Reverse words without changing the spacing.
Example
Input
Java is awesome
Normal Output
awesome is Java
Required Output
awesome is Java
This variation requires recording the positions of spaces while reversing only the words.
Reverse Each Word Instead of Word Order
This is another common variation.
Input
Java Spring Boot
Output
avaJ gnirpS tooB
Notice
The word order remains the same.
Only individual words are reversed.
Java Program
public class ReverseEachWord {
public static String reverseEachWord(String input) {
String[] words = input.split(" ");
StringBuilder result = new StringBuilder();
for (String word : words) {
result.append(
new StringBuilder(word).reverse());
result.append(" ");
}
return result.toString().trim();
}
public static void main(String[] args) {
System.out.println(
reverseEachWord("Java Spring Boot"));
}
}
Output
avaJ gnirpS tooB
Unicode Considerations
Java strings are Unicode.
Examples
こんにちは 世界
नमस्ते दुनिया
😊 Hello 🌍
The solutions shown work correctly for most Unicode text because Java String supports Unicode.
However, when working with supplementary Unicode characters (such as many emoji), be aware that a single visual character may consist of multiple UTF-16 code units. For advanced internationalization, consider processing Unicode code points instead of individual char values.
Edge Cases
| Input | Expected Output |
|---|---|
"" |
"" |
"Java" |
Java |
"Hello World" |
World Hello |
" Java Spring " |
Spring Java (after trimming) |
"a b c" |
c b a |
null |
Handle appropriately based on application requirements |
Time & Space Complexity
| Approach | Time | Extra Space |
|---|---|---|
| split() + Reverse Traversal | O(n) | O(n) |
| StringTokenizer | O(n) | O(n) |
| Two Pointers | O(n) | O(n) |
| Stack | O(n) | O(n) |
| Java Streams | O(n) | O(n) |
Where:
- n = length of the input string.
Comparison of All Approaches
| Approach | Interview Friendly | Performance | Easy to Understand |
|---|---|---|---|
| split() + Reverse Traversal | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| StringTokenizer | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Two Pointers | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| Stack | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Java Streams | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
Common Interview Mistakes
Mistake 1
Confusing reversing words with reversing characters.
Wrong
Java
↓
avaJ
Correct
Java Spring
↓
Spring Java
Mistake 2
Leaving an extra space at the end.
Wrong
World Hello
(with a trailing space)
Correct
return result.toString().trim();
Mistake 3
Ignoring multiple spaces.
Input
Java Spring
Clarify whether spaces must be preserved.
Mistake 4
Using string concatenation inside loops.
Wrong
result = result + word;
Better
StringBuilder result = new StringBuilder();
Mistake 5
Not checking for empty input.
Always test
""
"Java"
null
Interview Follow-up Questions
Q1. Reverse words without using split().
Q2. Reverse each individual word.
Q3. Reverse words while preserving multiple spaces.
Q4. Reverse the sentence in place.
Q5. Which solution is the most efficient?
Q6. How would you solve it using a stack?
Q7. How would you solve it using Java Streams?
Q8. Can you reverse words in a character array?
Q9. How do you handle Unicode text?
Q10. What is the time complexity?
Related Problems
- Reverse String
- Reverse Each Word
- Palindrome String
- Remove Duplicate Characters
- String Anagram
- Longest Word in a Sentence
- Word Pattern
- Longest Substring Without Repeating Characters
Key Takeaways
- Reversing words means reversing the order of words, not the characters inside them.
- The
split()+ reverse traversal approach is the simplest and most commonly used interview solution. - The Two Pointer approach is useful when
split()is not allowed. - A Stack naturally reverses word order because of its LIFO behavior.
- Java Streams provide a concise functional solution but are less common in coding interviews.
- Always clarify whether multiple spaces, punctuation, or Unicode characters require special handling.
Frequently Asked Interview Questions
Q1. Which approach is best for interviews?
The split() + Reverse Traversal approach is the easiest to explain and is accepted in most coding interviews.
Q2. Which solution is the most optimized?
The Two Pointer solution is preferred when interviewers restrict the use of split() because it scans the string directly while maintaining O(n) time complexity.
Q3. Why use StringBuilder?
StringBuilder avoids creating many temporary String objects, making repeated appends much more efficient than string concatenation.
Q4. Can words be reversed without extra space?
Yes. It is possible to reverse words in-place when working with mutable character arrays, although the implementation is more complex.
Q5. How is reversing words different from reversing characters?
Example
Input
Java Spring
Reverse Characters
gnirpS avaJ
Reverse Words
Spring Java
These are different interview problems and require different approaches.
Interview Tip
If an interviewer asks:
"Reverse the words in a sentence."
Start with the split() + Reverse Traversal solution because it is simple, readable, and demonstrates strong knowledge of Java strings.
Then discuss additional approaches:
split()+ reverse traversal (most common)StringTokenizer(legacy Java API)- Two Pointers (without using
split()) - Stack (LIFO-based solution)
- Java Streams (Java 8+ functional style)
Finally, ask clarifying questions such as:
- Should multiple spaces be preserved?
- Should punctuation remain attached to words?
- Can I use built-in methods like
split()? - Is the input guaranteed to be non-null?
Clarifying requirements before coding demonstrates strong communication skills and interview readiness.