← Back to libraryQuestion 54 of 273
⌨️Java CodingBeginner

Reverse a String

📌 Definition:

Return a string with its characters in reverse order (e.g. "hello" -> "olleh"). The classic warm-up that checks basic indexing and immutability awareness.

📖 Detailed Explanation:

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.

💻 Solutions:
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))
🔑 Key Points:
  • Strings are immutable — build a new value
  • Two-pointer swap is O(n) time
  • Know the one-liners per language
  • Handle null/empty defensively
🌍 Real-World Example:

Reversing strings underpins palindrome checks and building deterministic keys; more often, it is the opening question that sets the tone in a coding screen.

🎯 Scenario-Based Interview Question:

A candidate reverses with result += s.charAt(i) in a loop. For a very long string, what is the performance problem?