Reverse a String
Solve the classic Reverse String problem using various approaches.
🧩 Problem Statement
Write a function to reverse a string without using built-in functions like StringBuilder.reverse()
.
✍️ Function Signature
public String reverseString(String s)
🚀 Approaches
🧠 1. Two-Pointer Technique
Swap characters from both ends moving toward the center.
public String reverseString(String s) {
char[] chars = s.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
🔁 2. Using a Char Array and Iteration
Build the reversed string manually.
public String reverseString(String s) {
char[] input = s.toCharArray();
String result = "";
for (int i = input.length - 1; i >= 0; i--) {
result += input[i]; // Note: inefficient for large strings
}
return result;
}
🧱 3. Using a Character Stack (Simulating Recursion Stack)
Good for interview discussion on stack usage.
public String reverseString(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
stack.push(c);
}
StringBuilder reversed = new StringBuilder();
while (!stack.isEmpty()) {
reversed.append(stack.pop());
}
return reversed.toString();
}
🧮 4. Recursion
Elegant but less performant due to overhead.
public String reverseString(String s) {
if (s == null || s.length() <= 1) {
return s;
}
return reverseString(s.substring(1)) + s.charAt(0);
}
🧪 Test Cases
public class ReverseStringTest {
public static void main(String[] args) {
test("hello", "olleh");
test("racecar", "racecar");
test("12345", "54321");
test("A", "A");
test("", "");
}
private static void test(String input, String expected) {
TwoSumSolver solver = new TwoSumSolver();
String result = solver.reverseString(input);
System.out.println("Input: " + input);
System.out.println("Output: " + result);
System.out.println("Expected: " + expected);
System.out.println(result.equals(expected) ? "✅ Passed" : "❌ Failed");
System.out.println("-----------------------------");
}
}
📝 Notes
- Avoid
+=
string concatenation for long inputs in interviews—mention usingStringBuilder
. - Recursive solution may be less efficient due to call stack depth.
- Talk through edge cases like empty strings, single characters, and palindromes.
Happy coding! 🔄
Related Posts
Java Interview Guide - Part 4: Advanced Java Concepts (Q31–Q40)
A comprehensive list of essential Java interview questions covering OOP, memory management, exceptions, collections, and Streams
Java Interview Guide - Part 0: Core Questions (1–50)
A comprehensive list of essential Java interview questions covering OOP, memory management, exceptions, collections, Streams, JDBC
Java Interview Guide - Part 2: Advanced Java Concepts (Q11–Q20)
A comprehensive list of essential Java interview questions covering OOP, memory management, exceptions, collections, Streams, JDBC.