Reverse String

Java coding interview problem for String Coding: Reverse String.

String manipulation is one of the most fundamental topics in programming, and Reverse String is often the first string problem asked during Java coding interviews.

Although the problem looks simple, interviewers use it to evaluate multiple programming concepts, including:

  • String handling
  • Character manipulation
  • Arrays
  • Two Pointer Algorithm
  • Recursion
  • Time Complexity
  • Space Optimization

Most interviewers don't stop after asking you to reverse a string.

They often ask follow-up questions like:

  • Can you reverse it without using library methods?
  • Can you reverse it in-place?
  • Can you reverse only words?
  • Can you reverse only vowels?
  • Which approach is the most efficient?

Understanding all possible solutions prepares you for these advanced interview scenarios.


Problem Statement

Given a string, reverse all its characters.

Example 1

Input

hello

Output

olleh

Example 2

Input

Java

Output

avaJ

Example 3

Input

CodeWithVenu

Output

uneVhtiWedoC

Why Reverse String is Asked in Interviews?

Although reversing a string appears easy, it helps interviewers evaluate several important programming concepts.

They can assess whether a candidate understands:

  • Strings
  • Arrays
  • Character indexing
  • Looping techniques
  • Recursion
  • Two Pointer Algorithm
  • Space optimization
  • Java library usage

This problem is also the foundation for many advanced interview questions.

Examples include:

  • Valid Palindrome
  • Reverse Words
  • Reverse Vowels
  • Reverse Every Word
  • Rotate String
  • Anagram Detection

Real-World Applications

Reverse String is not only an interview problem.

It has practical applications in software development.

Text Processing

Many text editors reverse text during transformations.


DNA Sequence Analysis

Bioinformatics software frequently reverses DNA sequences.


Encryption

Some simple encryption algorithms reverse characters before encoding.


Data Compression

Certain compression algorithms perform reverse traversal while processing data.


Compiler Design

Lexical analyzers sometimes scan text from both directions.


Palindrome Checking

Palindrome algorithms compare a string with its reversed version.


Understanding Strings in Java

Before solving the problem, it is important to understand how Java stores strings.

Example

String str = "HELLO";

Memory representation

+---+---+---+---+---+
| H | E | L | L | O |
+---+---+---+---+---+
 0   1   2   3   4

Each character has an index.

These indexes allow us to access characters individually.

Example

str.charAt(0)

Output

H

str.charAt(4)

Output

O

Immutable Strings vs Mutable Objects

One of the most common interview questions related to Reverse String is:

Why can't we modify a String directly?

Because Java Strings are immutable.

Example

String str = "Java";

str.concat(" Programming");

System.out.println(str);

Output

Java

The original string does not change.

Instead, a new String object is created.


Mutable Objects

Java provides mutable alternatives.

Example

StringBuilder sb = new StringBuilder("Java");

sb.reverse();

System.out.println(sb);

Output

avaJ

StringBuilder modifies the existing object instead of creating a new String.


Mathematical Concept

Suppose

HELLO

Indexes

0 1 2 3 4

Characters

H E L L O

Reverse traversal

4 3 2 1 0

Result

O L L E H

The algorithm simply starts from the last index and moves toward the first index.


Visual Representation

Input

HELLO
+---+---+---+---+---+
| H | E | L | L | O |
+---+---+---+---+---+
 0   1   2   3   4

Traversal

4 → 3 → 2 → 1 → 0

Output

O L L E H

Dry Run

Input

JAVA

Length

4

Indexes

0 1 2 3

Characters

J A V A

Iteration 1

Index = 3

Character = A

Result = A

Iteration 2

Index = 2

Character = V

Result = AV

Iteration 3

Index = 1

Character = A

Result = AVA

Iteration 4

Index = 0

Character = J

Result = AVAJ

Final Output

AVAJ

Approach 1 — Using StringBuilder.reverse()

This is the easiest and most commonly used solution in real-world Java applications.

Java provides a built-in reverse() method inside the StringBuilder class.


Java Program

public class ReverseString {

    public static void main(String[] args) {

        String input = "Hello";

        String reversed =
                new StringBuilder(input)
                        .reverse()
                        .toString();

        System.out.println(reversed);

    }

}

Output

olleH

How Does StringBuilder.reverse() Work?

Suppose

JAVA

Initially

J A V A

After calling

reverse()

Characters become

A V A J

The method internally swaps characters from both ends until it reaches the middle.

Conceptually:

Left  → ← Right

Swap

J ↔ A

Then

A ↔ V

Result

A V A J

Step-by-Step Code Explanation

String input = "Hello";

Creates the input string.


new StringBuilder(input)

Creates a mutable object containing "Hello".


.reverse()

Reverses all characters.


.toString()

Converts the result back into a String.


Advantages

  • Very short code.
  • Highly readable.
  • Built into the Java API.
  • Preferred in production applications.
  • Efficient implementation.

Drawbacks

  • Uses a library method.
  • Interviewers may ask you to solve the problem without built-in methods.

Approach 2 — Using a Character Array

Another common interview solution is to convert the string into a character array and build the reversed string manually.

This demonstrates your understanding of arrays and character traversal.


Algorithm

  1. Convert the string into a character array.
  2. Traverse the array from the last index to the first.
  3. Append each character to a result string or StringBuilder.
  4. Return the reversed string.

Java Program

public class ReverseStringUsingCharArray {

    public static void main(String[] args) {

        String input = "Hello";

        char[] characters = input.toCharArray();

        StringBuilder result = new StringBuilder();

        for (int i = characters.length - 1; i >= 0; i--) {
            result.append(characters[i]);
        }

        System.out.println(result);

    }

}

Output

olleH

Dry Run

Input

HELLO

Character Array

[H, E, L, L, O]

Loop execution

Iteration Index Character Result
1 4 O O
2 3 L OL
3 2 L OLL
4 1 E OLLE
5 0 H OLLEH

Final Output

OLLEH

Step-by-Step Code Explanation

Convert the string to a character array.

char[] characters = input.toCharArray();

Create a mutable result.

StringBuilder result = new StringBuilder();

Traverse from the last character.

for (int i = characters.length - 1; i >= 0; i--)

Append each character.

result.append(characters[i]);

Print the reversed string.

System.out.println(result);

Time & Space Complexity

Approach Time Extra Space
StringBuilder.reverse() O(n) O(n)
Character Array O(n) O(n)

Where:

  • n = length of the input string.

Both approaches visit every character exactly once, resulting in linear time complexity.


Comparison of Approaches

Feature StringBuilder.reverse() Character Array
Easy to Write ✅ ✅
Interview Friendly ⚠️ Sometimes discouraged ✅
Manual Logic ❌ ✅
Performance Excellent Excellent
Best For Production code Coding interviews

Advantages of These Approaches

  • Simple to understand.
  • Efficient with O(n) time complexity.
  • Great introduction to string manipulation.
  • Frequently asked in Java interviews.
  • Forms the basis for advanced string algorithms.

Drawbacks

  • StringBuilder.reverse() hides the implementation details.
  • Character array approach requires additional memory.
  • Neither approach reverses the string in-place because Java String objects are immutable.

In Part 2, we'll explore more interview-oriented solutions, including:

  • Two Pointer Technique
  • Recursion
  • Stack-Based Reversal
  • Java Streams (Java 8+)
  • Reverse Words Instead of Characters
  • Reverse Each Word in a Sentence
  • Unicode Considerations
  • Comparison of All Approaches
  • Common Interview Mistakes
  • Edge Cases
  • Interview Questions
  • Related String Problems
  • Key Takeaways
  • Interview Tips

Approach 3 — Two Pointer Technique

The Two Pointer Technique is one of the most important interview approaches.

Instead of creating another array immediately, we use two indexes:

  • Left pointer starts from the beginning.
  • Right pointer starts from the end.
  • Swap characters until both pointers meet.

This is one of the most commonly expected interview solutions.


Visualization

Input

HELLO
 H  E  L  L  O
 ↑           ↑
Left       Right

Swap

 O  E  L  L  H
    ↑     ↑

Swap

 O  L  L  E  H
      ↑

Pointers meet.

Output

OLLEH

Java Program

public class ReverseStringTwoPointers {

    public static void main(String[] args) {

        String input = "Hello";

        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--;
        }

        System.out.println(new String(chars));

    }

}

Dry Run

Input

JAVA

Characters

J A V A

Iteration 1

Swap

J ↔ A

Result

A A V J

Iteration 2

Swap

A ↔ V

Result

A V A J

Pointers cross.

Final Output

AVAJ

Approach 4 — Using Recursion

Recursion solves the problem by reversing the smaller portion first.

Suppose

JAVA

Recursive calls

reverse("AVA")

↓

reverse("VA")

↓

reverse("A")

↓

reverse("")

While returning

A

↓

AV

↓

AVA

↓

AVAJ

Java Program

public class ReverseStringRecursion {

    static String reverse(String str) {

        if (str.isEmpty()) {
            return str;
        }

        return reverse(str.substring(1))
                + str.charAt(0);

    }

    public static void main(String[] args) {

        System.out.println(reverse("Hello"));

    }

}

Output

olleH

Advantages

  • Elegant solution.
  • Demonstrates recursion.
  • Frequently asked for recursion practice.

Drawbacks

  • Uses additional stack memory.
  • Slower because of repeated substring creation.
  • May cause StackOverflowError for very large strings.

Approach 5 — Using Stack

A Stack follows the Last-In, First-Out (LIFO) principle.

Example

Input

JAVA

Push

J

↓

A

↓

V

↓

A

Pop

A

↓

V

↓

A

↓

J

Output

AVAJ

Java Program

import java.util.Stack;

public class ReverseStringStack {

    public static void main(String[] args) {

        String input = "Hello";

        Stack<Character> stack = new Stack<>();

        for (char ch : input.toCharArray()) {
            stack.push(ch);
        }

        StringBuilder result = new StringBuilder();

        while (!stack.isEmpty()) {
            result.append(stack.pop());
        }

        System.out.println(result);

    }

}

Approach 6 — Using Java Streams (Java 8+)

Although not commonly used in production for string reversal, Java Streams demonstrate knowledge of the Stream API.


Java Program

import java.util.stream.Collectors;

public class ReverseStringStreams {

    public static void main(String[] args) {

        String input = "Hello";

        String reversed = input
                .chars()
                .mapToObj(c -> String.valueOf((char) c))
                .collect(Collectors.collectingAndThen(
                        Collectors.toList(),
                        list -> {
                            java.util.Collections.reverse(list);
                            return String.join("", list);
                        }
                ));

        System.out.println(reversed);

    }

}

Reverse Words Instead of Characters

Sometimes interviewers ask:

Reverse the order of words instead of characters.

Input

Java Spring Boot

Output

Boot Spring Java

Java Program

public class ReverseWords {

    public static void main(String[] args) {

        String input = "Java Spring Boot";

        String[] words = input.split(" ");

        for (int i = words.length - 1; i >= 0; i--) {
            System.out.print(words[i] + " ");
        }

    }

}

Reverse Each Word in a Sentence

Input

Java Spring

Output

avaJ gnirpS

Java Program

public class ReverseEachWord {

    public static void main(String[] args) {

        String sentence = "Java Spring";

        String[] words = sentence.split(" ");

        for (String word : words) {

            String reversed =
                    new StringBuilder(word)
                            .reverse()
                            .toString();

            System.out.print(reversed + " ");

        }

    }

}

Unicode Considerations

Most interview solutions assume English letters.

However, Java uses Unicode, not ASCII.

Example

こんにちは

or

😊🚀

Simple reversal by char may not correctly handle all Unicode characters because some symbols (such as many emoji) are represented by surrogate pairs.

For full Unicode correctness, consider processing Unicode code points instead of individual char values when required.


Edge Cases

Input Expected Output
"" ""
"A" "A"
"AA" "AA"
"12345" "54321"
"Hello World" "dlroW olleH"
" " " "
null Handle appropriately (throw exception or return null based on requirements)

Time & Space Complexity

Approach Time Extra Space
StringBuilder.reverse() O(n) O(n)
Character Array O(n) O(n)
Two Pointer O(n) O(n)*
Recursion O(n) O(n) (call stack)
Stack O(n) O(n)
Streams O(n) O(n)

Note: The two-pointer approach uses a character array because Java String objects are immutable. If you were reversing a mutable character array directly, the extra space for the algorithm itself would be O(1).


Comparison of All Approaches

Approach Interview Friendly Easy to Understand Performance
StringBuilder.reverse() ⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
Character Array ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
Two Pointer ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
Recursion ⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐
Stack ⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐
Streams ⭐⭐ ⭐⭐ ⭐⭐⭐

Common Interview Mistakes

Mistake 1

Using only:

new StringBuilder(str).reverse();

without understanding how it works.

Interviewers often ask you to implement the logic manually.


Mistake 2

Ignoring null input.

Always clarify the expected behavior.

Example

if (input == null) {
    return null;
}

Mistake 3

Using string concatenation inside a loop.

Wrong

result += ch;

Repeated concatenation creates many intermediate String objects because strings are immutable.

Better

StringBuilder builder = new StringBuilder();
builder.append(ch);

Mistake 4

Incorrect loop condition.

Wrong

left <= right

For swapping, prefer

left < right

to avoid unnecessary work on the middle character.


Mistake 5

Confusing character reversal with word reversal.

Example

Input

Java Spring

Character reversal

gnirpS avaJ

Word reversal

Spring Java

Always clarify the requirement before coding.


Interview Follow-up Questions

Q1. Reverse a string without using built-in methods.

Q2. Reverse only vowels.

Q3. Reverse only letters while keeping symbols fixed.

Q4. Reverse words instead of characters.

Q5. Check whether a string is a palindrome.

Q6. Reverse a character array in-place.

Q7. What is the most efficient solution?

Q8. Can recursion solve this problem?

Q9. How would you handle Unicode characters correctly?

Q10. What happens if the input is null?


Related Problems

  • Valid Palindrome
  • Reverse Words in a String
  • Reverse Vowels of a String
  • Reverse String II
  • Reverse Linked List
  • Rotate String
  • Check Anagram
  • Longest Palindromic Substring
  • String Compression

Key Takeaways

  • String reversal is one of the most fundamental string manipulation problems.
  • Java String objects are immutable, so reversing usually involves creating a new object or working with a mutable structure.
  • StringBuilder.reverse() is concise and practical for production code.
  • The Two Pointer Technique is the preferred manual solution in coding interviews.
  • Recursion and Stack-based solutions demonstrate alternative problem-solving techniques but use additional memory.
  • Always consider edge cases such as empty strings, single characters, and null values.
  • For applications requiring full Unicode support, process Unicode code points rather than individual char values.

Frequently Asked Interview Questions

Q1. Which approach is best for interviews?

The Two Pointer Technique is generally preferred because it demonstrates a clear understanding of character manipulation and swapping without relying on built-in APIs.


Q2. Why is StringBuilder.reverse() so fast?

StringBuilder stores characters in a mutable array and reverses them by swapping elements from both ends toward the center, avoiding repeated string creation.


Q3. Can a Java String be reversed in-place?

No. Java String objects are immutable. To perform in-place reversal, you must work with a mutable structure such as a char[] or StringBuilder.


Q4. Which solution uses the least additional memory?

If the input is already a mutable character array, the Two Pointer Technique performs the reversal with O(1) extra algorithmic space.


Q5. What should you ask before writing the solution?

Clarify:

  • Can built-in methods be used?
  • Is the input guaranteed to be non-null?
  • Should Unicode characters (including emoji) be handled correctly?
  • Should characters be reversed, or should words be reversed?

Interview Tip

If an interviewer asks:

"Reverse a string in Java."

Start with the Two Pointer Technique instead of immediately using StringBuilder.reverse(). Explain that:

  1. Convert the string to a mutable character array.
  2. Use two pointers (left and right).
  3. Swap characters while left < right.
  4. Convert the array back to a string.

After solving the problem, mention alternative approaches such as StringBuilder, recursion, stacks, and streams, along with their trade-offs. This demonstrates a strong understanding of algorithms, Java string internals, and practical software engineering decisions.