A warm-up coding question. The interviewer wants a correct loop, a clear explanation of cost, and maybe one edge case. Do not reach for new StringBuilder(s).reverse(): that is exactly what they asked you not to use.
The two-pointer swap (O(n) time, O(n) space)
Strings in Java are immutable, so copy the characters into an array, swap from both ends towards the middle, and build a new string.
static String reverse(String s) {
if (s == null) return null;
char[] a = s.toCharArray();
int i = 0, j = a.length - 1;
while (i < j) {
char t = a[i];
a[i] = a[j];
a[j] = t;
i++;
j--;
}
return new String(a);
}
Each character is touched once, so time is O(n). The char array takes O(n) extra space; in a language with mutable strings or arrays (C, or reversing a char array in place) the swap itself needs only O(1) extra space.
Building from the end
static String reverse2(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();
}
Avoid doing the same with result = result + s.charAt(i) in a loop: each concatenation creates a new string, which makes it O(n²).
Recursion (if they ask for it)
static String reverseRec(String s) {
if (s.length() <= 1) return s;
return reverseRec(s.substring(1)) + s.charAt(0);
}
Short, but O(n²) because of the substrings and concatenation, and it can overflow the stack for long strings. Say that before they ask.
Edge cases to mention
nulland the empty string.- A single character or a palindrome (the output equals the input).
- Characters outside the Basic Multilingual Plane, such as emoji, are two
chars (a surrogate pair). A plain char swap breaks them; reverse by code points if that matters.
Follow-ups
- Reverse each word in a sentence but keep the word order.
- Reverse the order of words: “I like Java” becomes “Java like I”.
- Check whether a string is a palindrome.
This answer was written by Debugger’s Space as practice material. It is asked in most Indian IT services interviews (TCS, Infosys, Wipro, HCLTech, Tech Mahindra, LTIMindtree, Accenture, Cognizant, Capgemini, IBM). See each company’s hiring steps and practice questions on Debugger’s Space.