Reverse a string and reverse the words of a sentence. How many ways can you do it in Java?
Problem
Reverse "hello" → "olleh"; reverse the word order of " the sky is blue " → "blue is sky the" (collapse extra spaces). The most frequently asked Java string question.
Pattern
Two pointers swapping in a char array, or library helpers. For word order: reverse the whole string, then each word (in place), or split and join.
Approach 1: Loop from the end with string concatenation (feasible but O(n²))
Each += creates a new String, so a long string costs quadratic time.
class ReverseConcat {
static String reverse(String s) {
String out = "";
for (int i = s.length() - 1; i >= 0; i--) out += s.charAt(i);
return out;
}
}Approach 2: StringBuilder.reverse() (O(n), the practical answer)
Also handles surrogate pairs correctly (emoji are not split).
class ReverseBuilder {
static String reverse(String s) { return new StringBuilder(s).reverse().toString(); }
}Approach 3: Char array with two pointers (O(n), shows the algorithm)
class ReverseTwoPointers {
static String reverse(String s) {
char[] c = s.toCharArray();
for (int i = 0, j = c.length - 1; i < j; i++, j--) { char t = c[i]; c[i] = c[j]; c[j] = t; }
return new String(c);
}
}Approach 4: Java 8 streams (concise, slower)
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class ReverseStreams {
static String reverse(String s) {
return IntStream.range(0, s.length()).mapToObj(i -> String.valueOf(s.charAt(s.length() - 1 - i))).collect(Collectors.joining());
}
}Reverse the words: three ways
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.stream.Collectors;
class ReverseWords {
// 1. split + Collections.reverse + join
static String withSplit(String s) {
List<String> words = Arrays.asList(s.trim().split("\\s+"));
Collections.reverse(words);
return String.join(" ", words);
}
// 2. Streams with a deque (Java 8)
static String withStreams(String s) {
return Arrays.stream(s.trim().split("\\s+"))
.collect(Collectors.toCollection(ArrayDeque::new))
.stream().reduce((a, b) -> b + " " + a).orElse("");
}
// 3. Manual scan from the end without split or regex: O(n), one StringBuilder
static String manual(String s) {
StringBuilder out = new StringBuilder();
int i = s.length() - 1;
while (i >= 0) {
while (i >= 0 && s.charAt(i) == ' ') i--;
if (i < 0) break;
int end = i;
while (i >= 0 && s.charAt(i) != ' ') i--;
if (out.length() > 0) out.append(' ');
out.append(s, i + 1, end + 1);
}
return out.toString();
}
// Java 21: SequencedCollection.reversed() view on a List
static String java21(String s) {
return String.join(" ", Arrays.asList(s.trim().split("\\s+")).reversed());
}
}
class ReverseDemo {
public static void main(String[] args) {
System.out.println(ReverseConcat.reverse("hello") + " " + ReverseBuilder.reverse("hello") + " "
+ ReverseTwoPointers.reverse("hello") + " " + ReverseStreams.reverse("hello")); // olleh x4
String sentence = " the sky is blue ";
System.out.println("[" + ReverseWords.withSplit(sentence) + "] [" + ReverseWords.withStreams(sentence) + "] ["
+ ReverseWords.manual(sentence) + "] [" + ReverseWords.java21(sentence) + "]"); // [blue is sky the] x4
}
}Feasible → optimal
String concatenation in a loop: O(n²) (the classic trap). StringBuilder.reverse() and two pointers: O(n). Streams: O(n) but with boxing and per-character strings. For words, a manual scan avoids regex and intermediate arrays; split + reverse + join is the readable choice; Java 21's reversed() makes it one line.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related (same pattern): reverse each word but keep the word order.
Split on spaces and reverse each token (Arrays.stream(s.split(" ")).map(w -> new StringBuilder(w).reverse().toString()).collect(joining(" "))), or scan once and reverse each run of non-space characters in a char array with two pointers. O(n).
Related (same pattern): check if a string is a rotation of another.
a.length() == b.length() && (a + a).contains(b). O(n) with a good substring search (KMP); the JDK's contains is fine in practice.