Return a string with its characters in reverse order (e.g. "hello" -> "olleh"). The classic warm-up that checks basic indexing and immutability awareness.
Convert the string to a character array (or iterate from the last index) and swap from both ends toward the middle, or build the result backwards. Strings are immutable in Java, so you cannot mutate the original in place. The two-pointer swap is O(n) time and O(n) space.
public static String reverse(String s) {
char[] c = s.toCharArray();
int i = 0, j = c.length - 1;
while (i < j) {
char t = c[i]; c[i++] = c[j]; c[j--] = t;
}
return new String(c);
}function reverse(s) {
return s.split('').reverse().join('');
}
// manual: let out=''; for (let i=s.length-1;i>=0;i--) out+=s[i];def reverse(s):
return s[::-1]
# manual: return ''.join(reversed(s))Reversing strings underpins palindrome checks and building deterministic keys; more often, it is the opening question that sets the tone in a coding screen.
A candidate reverses with result += s.charAt(i) in a loop. For a very long string, what is the performance problem?