Back to Arrays
Q1Question 1 of 109

Reverse a string

Key Concepts
  • Strings in Java are immutable, so reversing requires creating a new character sequence.
  • The cleanest production approach is new StringBuilder(s).reverse().toString(), which also handles surrogate pairs correctly.
  • The manual approach converts to a char array and uses two-pointer swaps, mirroring the array reversal pattern.
  • Both approaches are O(n) time and O(n) space because a new string must be allocated.
  • StringBuilder.reverse is preferred in production because it correctly handles Unicode surrogate pairs.
  • This is a common interview warm-up that tests understanding of immutability and pointer control.

Definition

Build a new string with the characters flipped: swap from both ends of a char array, or use StringBuilder.reverse().
  • Immutability – Java String cannot be reversed in place; a new character sequence must be created.
  • StringBuilder approach – new StringBuilder(s).reverse().toString() is concise, correct, and handles surrogate pairs.
  • Manual approach – convert to char[] and swap with two pointers, then build a new String from the array.
  • O(n) time – every character is visited once.
  • O(n) space – a new string of the same length must be allocated.

National Bank of India generates a reversed reference code from a transaction id for a simple checksum. Rajesh's id "TXN123" becomes "321NXT". A clerk writes the characters out backwards onto a new slip, because the original id slip cannot be rewritten.

Understanding the Concepts

What is the problem?

Given a string, produce a new string with the characters in reversed order. In a banking context, Rajesh's transaction reference "TXN123" at National Bank of India is reversed to "321NXT" as a lightweight verification code printed on the receipt.

Why can you not reverse a String in place in Java?

Java's String class is immutable. Once created, its characters cannot be changed. Any "reversal" must create a new String. This is a design choice that makes strings safe for use as HashMap keys, thread-safe by default, and suitable for the string pool.

How do you reverse using StringBuilder?

StringBuilder is a mutable character buffer. Its reverse() method flips the characters in place inside the builder, and toString() produces the final String.

JAVA
package com.bank.service;

public class ReferenceCodeGenerator {

    public static String reverseWithBuilder(String input) {
        if (input == null) {
            throw new IllegalArgumentException("Input cannot be null");
        }
        return new StringBuilder(input).reverse().toString();
    }

    public static void main(String[] args) {
        String txnId = "TXN123";
        String reversed = reverseWithBuilder(txnId);
        System.out.println("Original:  " + txnId);
        System.out.println("Reversed:  " + reversed);
    }
}
TEXT
Original:  TXN123
Reversed:  321NXT

How do you reverse manually with a char array?

Convert the string to a char[], apply the two-pointer swap technique from both ends, and build a new String from the modified array.

JAVA
public static String reverseManual(String input) {
    if (input == null) {
        throw new IllegalArgumentException("Input cannot be null");
    }
    char[] chars = input.toCharArray();
    int left = 0;
    int right = chars.length - 1;
    while (left < right) {
        char temp = chars[left];
        chars[left] = chars[right];
        chars[right] = temp;
        left++;
        right--;
    }
    return new String(chars);
}

How do the two approaches compare?

| Aspect | StringBuilder.reverse() | Manual char[] swap |
|---|---|---|
| Code length | One line | 10+ lines |
| Surrogate pairs | Handled correctly | Broken by naive swap |
| Performance | Same O(n) | Same O(n) |
| Interview value | Shows API knowledge | Shows pointer control |

What is the Unicode surrogate pair problem?

A single visible character outside the Basic Multilingual Plane (like certain emoji or rare scripts) is stored as two char values called a surrogate pair. Naive char-by-char reversal splits the pair, producing a corrupted string. StringBuilder.reverse detects surrogate pairs and keeps them intact, which is one reason to prefer it in production.

JAVA
// Surrogate pair example
String emoji = "A\uD83D\uDE00B"; // A😀B
String broken = reverseManual(emoji);  // may corrupt the emoji
String correct = reverseWithBuilder(emoji); // keeps emoji intact

What is the time and space complexity?

  • Time: O(n) because every character is visited once.
  • Space: O(n) because a new string of the same length must be allocated. The original string is immutable and unchanged.

What are common mistakes?

The most common mistake is trying to use recursion, which creates O(n) stack frames and O(n^2) string concatenation if done naively. Another mistake is forgetting that String is immutable and expecting in-place modification.

JAVA
// Wrong: O(n^2) recursive approach
public static String reverseRecursive(String s) {
    if (s.isEmpty()) return s;
    return reverseRecursive(s.substring(1)) + s.charAt(0);
    // Each + creates a new String, total work is O(n^2)
}

// Correct: use StringBuilder or char[] swap for O(n)

What should a senior engineer know?

A senior engineer prefers StringBuilder.reverse in production for surrogate pair safety and recommends the char-array approach only in an interview to demonstrate two-pointer mechanics. The senior also knows that for very large strings, the char-array approach avoids the overhead of StringBuilder's internal capacity management, but in practice the difference is negligible. If the reversed string is only needed for comparison, such as a palindrome check, the senior avoids creating the reversed string at all and instead compares characters from both ends directly.

Visual Overview

DIAGRAM
  Manual char[] swap:

  chars[]:  T  X  N  1  2  3
            │                 │
          left=0          right=5
  Step 1:  swap(T, 3)  → 3  X  N  1  2  T
           left=1       right=4
  Step 2:  swap(X, 2)  → 3  2  N  1  X  T
           left=2       right=3
  Step 3:  swap(N, 1)  → 3  2  1  N  X  T
           left=3       right=2  → stop

  Result: "321NXT"

Key Takeaway

Reversing a string produces a new string with the characters in the opposite order. Because a String in Java is immutable, I cannot reverse it in place, so I must create a new sequence of characters. The clean production approach is to wrap the string in a StringBuilder, call its reverse method, and convert back to a String. The manual approach is to convert the string to a character array and use two pointers from each end, swapping and moving inward until they meet.

In my banking project at National Bank of India, I used string reversal to generate a lightweight verification reference from a transaction id, printed on the customer's receipt. Rajesh's transaction id becomes its reverse as a simple checksum-style code.

The nuance I raise in an interview is Unicode correctness. A single visible character can be made of a surrogate pair of two underlying char values, and a naive character-by-character reversal can split and corrupt that pair. StringBuilder.reverse is aware of surrogate pairs and keeps them intact, which is why I prefer it in production over hand-rolled reversal.

Remember one sentence: use StringBuilder.reverse for production safety, and the char-array two-pointer swap to show the interviewer you understand the mechanics.

---

Share
Use ← → arrow keys to navigate