Category: Easy/Medium | Concepts used: String parsing, token splitting, StringBuilder buffer manipulation, regex bounds
Problem Statement
Given a sentence, reverse the letters within each word, but keep the order of the words unchanged.
Input : "Hello World" Output: "olleH dlroW"
Input : "I am here" Output: "I ma ereh"
Warning: Don’t confuse this with reversing the order of words (e.g.,
"Hello World"→"World Hello"), which is a different problem. Here, only the characters inside each individual word are flipped, while the words themselves stay in their original positions.
Examples (with edge scenarios)
| # | Input | Output | Why |
|---|---|---|---|
| 1 | "Hello World" | "olleH dlroW" | Each word is individually reversed |
| 2 | "" | "" | Empty string check |
| 3 | "I am here" | "I ma ereh" | Single-character word "I" remains unchanged |
| 4 | " hi there " | Clarify | Do we preserve multiple/outer spaces or collapse them? |
| 5 | "racecar level" | "racecar level" | Individual words are palindromes |
⚠️ Common Beginner Mistake
Mistake Impact Fix Reversing the entire sentence at once Reorders the words ( "here am I"), which is incorrectSplit the sentence into words first, reverse each word, then rejoin Splitting by a single space " "with irregular inputCreates empty ""tokens in the array, causing space corruptionUse split("\\s+")to split on multiple consecutive whitespaces
Before You Code: Clarify the Contract
Before choosing an algorithm, confirm how null and empty strings should behave, whether comparison is case-sensitive, and whether spaces or punctuation count. Java char values are UTF-16 code units, not always complete human-visible Unicode characters, so international text may require code points or grapheme-aware libraries.
Analogy: Mirroring Books on a Bookshelf
Imagine you have a bookshelf containing a series of books (words), arranged from left to right:
- Wrong problem (Reversing book order): You swap the physical positions of the books themselves, putting the last book first and the first book last. This changes the sequence of titles (
"World Hello"). - This problem (Reversing inside books): You leave the books in their exact positions on the shelf. Instead, you open each book and print its letters backwards. Book 1 remains on the left, but now reads “olleH”. Book 2 remains on the right, but now reads “dlroW”. The book sequence is untouched, but the inner contents are mirrored!
Solution 1 — Split into Words, Reverse Each, Rejoin
This is the standard iterative approach using split() and StringBuilder.
Intuition
This problem breaks down into: (1) splitting a sentence into individual word tokens, (2) reversing each token, and (3) rejoining the reversed tokens back into a sentence with single space separations.
public class ReverseEachWord {
public static String reverseWords(String sentence) {
if (sentence == null || sentence.isEmpty()) {
return sentence;
}
// Split by spaces. For multiple spaces, use "\\s+"
String[] words = sentence.split("\\s+");
StringBuilder result = new StringBuilder();
for (int i = 0; i < words.length; i++) {
// Reverse individual word using StringBuilder
String reversedWord = new StringBuilder(words[i]).reverse().toString();
result.append(reversedWord);
// Add trailing space between words (skip for the last word)
if (i != words.length - 1) {
result.append(" ");
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(reverseWords("Hello World")); // "olleH dlroW"
System.out.println(reverseWords("I am here")); // "I ma ereh"
System.out.println(reverseWords("")); // ""
}
}
Output:
olleH dlroW
I ma ereh
Solution 2 — Using Java Streams (Modern & Declarative)
This approach uses streams to transform and join word tokens in a single pipeline.
Intuition
By using Arrays.stream() to stream the split tokens, we can use .map() to apply the reversal function to each word, and collect them back using Collectors.joining(" ").
import java.util.Arrays;
import java.util.stream.Collectors;
public class ReverseEachWordStream {
public static String reverseWords(String sentence) {
if (sentence == null || sentence.isEmpty()) {
return sentence;
}
return Arrays.stream(sentence.split("\\s+"))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
}
public static void main(String[] args) {
System.out.println(reverseWords("Hello World")); // "olleH dlroW"
}
}
📊 Visual Flowchart
graph TD
Start["Input Sentence S"] --> NullCheck{"S is null/empty?"}
NullCheck -->|Yes| RetSelf["Return S"]
NullCheck -->|No| Split["words = S.split('\\s+')"]
Split --> InitBuilder["Initialize StringBuilder sb"]
InitBuilder --> Loop{"Iterate i from 0 to words.length - 1"}
Loop -->|Yes| Rev["reversedWord = reverse(words[i])"]
Rev --> Append["sb.append(reversedWord)"]
Append --> CheckEnd{"i == words.length - 1?"}
CheckEnd -->|No| AppendSpace["sb.append(' ')"]
CheckEnd -->|Yes| IncLoop["i++"]
AppendSpace --> IncLoop
IncLoop --> Loop
Loop -->|No| Convert["sb.toString()"]
Convert --> End["Return result"]
Interviewer Insights
This question tests string parsing, regular expression boundaries, and modular logic flow.
Follow-up questions you might get:
- “What is the time and space complexity?” → Time complexity is (O(N)) where (N) is the number of characters in the sentence, since we parse every character to split and reverse. Space complexity is (O(N)) to store the split words array and the resulting output builder.
- “How can you solve this in-place on a character array without split() to achieve O(1) auxiliary space?” → You can traverse a character array, identify word boundaries (spaces), and reverse the characters between boundaries in-place using a helper function:
You iterate through the array, finding the start and end indices of each word, and pass them topublic static void reverseInPlace(char[] chars, int left, int right) { while (left < right) { char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; left++; right--; } }reverseInPlace(). This avoids allocating string arrays or token matrices!
Quick Recap
| Approach | Space Complexity | Time Complexity | Handles Multiple Spaces? | Interview Signal |
|---|---|---|---|---|
| Split + Loop | (O(N)) | (O(N)) | Yes (using \\s+) | Clear, modular logic, safe for spacing anomalies |
| Stream API | (O(N)) | (O(N)) | Yes (using \\s+) | Concise expression of functional transformations |
| In-place char[] Traverse | (O(1)) (excluding input copy) | (O(N)) | Requires custom index skipping | Highly advanced, demonstrates deep pointer control |
- Author
- TechByteByByte Editorial Team
- Reviewed by
- TechByteByByte Admin
- Published
- Last reviewed