Java String Program · S01
Reverse a String in Java
Reversing a string is the classic warm-up question. Interviewers usually forbid StringBuilder.reverse() to see whether you can move characters yourself.
Problem Statement
Write a method reverse(String s) that returns the characters of s in reverse order, without calling StringBuilder.reverse().
Java strings are immutable, so the method must build and return a new string. An empty string and a single character return themselves.
Input/Output Examples
"JavaByTechie"Output"eihceTyBavaJ"Explanation: the last character comes first."level"Output"level"Explanation: a palindrome reads the same both ways."hello world"Output"dlrow olleh"Explanation: spaces are characters too and move with the rest.""Output""Explanation: there is nothing to swap.Visual Explanation
- Step 1left = 0, right = 4helloswap h and o
- Step 2left = 1, right = 3oellhswap e and l
- Step 3left = 2, right = 2ollehleft < right is false middle stays
- Donenew String(chars)"olleh"
"hello" with two pointers: the pair being swapped is highlighted (amber), swapped characters turn purple, and the middle character stays where it is.A string of length n needs only n / 2 swaps, because each swap puts two characters in their final places.
Approaches
Both approaches return a new reversed string. The first swaps characters in a copy of the string; the second reads the string backwards.
Approach 1: Two Pointers on a char Array (Recommended)
Idea: copy the string into a char[], swap the outermost pair, move both pointers inward and repeat until they meet.
- Call
s.toCharArray()to get a copy you can change. - Set
left = 0andright = length - 1. - While
left < right, swap the two characters and move both pointers. - Return
new String(chars).
Time: O(n) · Space: O(n). the array is a copy, because strings cannot be changed in place.
Approach 2: Backward Loop With StringBuilder
Idea: start at the last index and append each character to a StringBuilder until you reach index 0.
- Create a
StringBuilderwith the string's length as its capacity. - Loop
ifromlength - 1down to 0. - Append
s.charAt(i)each time and return the result.
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Two Pointers on a char Array (Recommended)
The standard interview answer; the same loop reverses arrays and lists.
public class ReverseStringTwoPointer {
// Swap the first and last characters, then move both pointers inward until they meet
static String reverse(String s) {
char[] chars = s.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char tmp = chars[left];
chars[left] = chars[right];
chars[right] = tmp;
left++;
right--;
}
return new String(chars);
}
public static void main(String[] args) {
String[] inputs = {"JavaByTechie", "level", "a", "", "hello world"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> \"" + reverse(s) + "\"");
}
}
}
"JavaByTechie" -> "eihceTyBavaJ" "level" -> "level" "a" -> "a" "" -> "" "hello world" -> "dlrow olleh"
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Backward Loop With StringBuilder
Very readable. Avoid result = s.charAt(i) + result in a loop, which copies the string every time and takes O(n2) time.
public class ReverseStringBackward {
// Read the string from the last index to the first and append each character
static String reverse(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
public static void main(String[] args) {
String[] inputs = {"JavaByTechie", "level", "a", "", "hello world"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> \"" + reverse(s) + "\"");
}
}
}
"JavaByTechie" -> "eihceTyBavaJ" "level" -> "level" "a" -> "a" "" -> "" "hello world" -> "dlrow olleh"
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Two Pointers on a char Array | O(n) | O(n) |
| Backward Loop With StringBuilder | O(n) | O(n) |
Both approaches visit each character once and build one new string of length n. The two-pointer loop runs only n / 2 times, but each iteration moves two characters.
Interview Tips and Recommended Approach
- Say that strings are immutable; any reversal builds a new string.
- Avoid string concatenation in a loop. It is
O(n2)because every+copies the whole string. - Mention surrogate pairs. Emoji take two
chars; reversing them separately breaks them, whileStringBuilder.reverse()keeps them together. - Handle
nullby agreeing a rule first: returnnullor throw an exception.
Recommended Approach: Two Pointers on a char Array
Why: it shows the two-pointer technique, does only n / 2 swaps and is the same pattern used in many later array and string problems.