Scrivio Interview library
Strings and triesArrays and stringsReported 45 times · 14 min read · updated 15 November 2026

Write a program that outputs a string's characters in reverse order.

1What it means to reverse the characters

Picture five books standing on a shelf, and you are asked to put them in the opposite order. You would not take all five down and line them up again from scratch. You would swap the two books at the ends, then the next two in from each end, and keep stepping inwards until you meet in the middle. That is the method we will build, and the books will help us at every step.

In Java a string is a sequence of characters, and each character has a position called its index. Indexes start at 0, so in "hello" index 0 holds h, index 1 holds e, and the last index, 4, holds o. To reverse the string means to produce the characters in the opposite order, so "hello" becomes "olleh". The problem is as small as it looks, and the only care needed is in the details.

Let us do it by hand. Write h, e, l, l, o in five boxes numbered 0 to 4. The character at index 0 must go to index 4, and the one at index 4 to index 0, so swap h and o. The character at index 1 must go to index 3, so swap e and the second l. Now the only box left is index 2, the middle l, and its mirror position is itself, so it stays. The boxes read o, l, l, e, h. Two swaps reversed five characters.

PictureThe word hello and the answer we want

The numbers above the boxes are the positions, called indexes. Each character must end up at its mirror position.

  1. h0e1l2l3o4firstlast
    input
    hello
    answer
    olleh
    pairs to swap
    (0, 4) and (1, 3)
    middle
    index 2 stays

    1In hello, index 0 holds h and index 4 holds o. In the answer olleh, they trade places, and so do e and the second l. The middle l stays put.

What to assume

Do we print the characters, or return the reversed string?
Most interviewers mean a method that returns the reversed string, because it can be tested and reused, so we return it.
What should null do?
We return null. The empty string and a single character reverse to themselves.
And can the text contain emoji?
We treat the string as a sequence of Java char values, which is right for ordinary text.

The question says outputs, so some interviewers are happy if we simply print the characters from last to first. Most mean a method that returns the reversed string, because it can be tested and reused, so we will write that and show the two line printing loop too. A careful candidate also asks what null should do; we return null. The empty string and a single character reverse to themselves. And can the text contain emoji? We treat the string as a sequence of Java char values, which is right for ordinary text, and come back to emoji at the end.

2How to recognise the strings pattern behind it

A beginner who meets this question usually thinks of walking backwards through the string and building the answer one character at a time. That is a natural first idea, and we will try it next. Before that, let us read the question for clues, because they point to something better.

The first clue is the word string, together with the fact that we must rearrange its characters rather than search in them. Strings in Java have one property that shapes every solution: a String object can never be changed after it is made, which is called being immutable. So any rearranging has to happen in a copy we are allowed to change, and the usual copy is a char array, a plain row of characters.

The second clue is the word reverse and what it does to positions. The character at index 0 goes to the last index, n - 1, where n is the length. The character at index 1 goes to n - 2. In general, index i trades places with index n - 1 - i, its mirror. So the work pairs the first position with the last, the second with the second to last, and moves inwards, just like the books.

These clues place the problem in the strings and tries family, problems about sequences of characters. A trie, a tree that stores many words by their shared beginnings, belongs to the same family but helps with searching many words, not with rearranging one, so we will not need it. The technique we do need is two pointers from both ends: two index variables, one starting at each end of the array, that move towards each other. The general rule to carry to new problems is that when position i must be matched or exchanged with its mirror n - 1 - i, two indexes from both ends can do the work in one pass.

A sliding window looks similar because it also keeps two indexes, but both move in the same direction to examine a stretch of the string. And a stack, the pile of plates where the last plate on is the first off, does reverse the order, but it stores every character a second time to do what one swap does directly. The same two pointer shape will come back when you check palindromes or reverse the words of a sentence.

3The honest first attempt, building the answer with +

The first loop most people write is short and clear. Walk the string from the last index down to 0, and add each character to the end of a result string with the + operator. On hello it adds o, then l, then l, then e, then h, and returns olleh. It is correct, and a correct brute force is always a good start.

Step throughConcatenation copies the same characters again and again

Each frame is the new String made by one + in the loop. Marked cells were copied again from the previous String; the highlighted cell is the one new character.

  1. o0
    result
    o
    this step
    1 written
    in all
    1 written

    1The loop starts at the last index and adds o to the empty result. A new String of one character is made, so one character is written.

  2. o0l1
    result
    ol
    this step
    2 written
    in all
    3 written

    2Adding l cannot change the old String, so Java builds a new one, copying o again and writing l. Two characters written, three in all.

  3. o0l1l2
    result
    oll
    this step
    3 written
    in all
    6 written

    3The next l means another new String: o and l are copied a second time and l is added. Three written, six in all.

  4. o0l1l2e3
    result
    olle
    this step
    4 written
    in all
    10 written

    4Adding e copies the first three characters yet again. Four written, ten in all, for a word of only five letters.

  5. o0l1l2e3h4
    result
    olleh
    this step
    5 written
    in all
    15 written

    5The last step copies four old characters to add h. Fifteen characters were written to build a five character answer.

Java
static String reverseByConcat(String s) {
String result = "";
for (int i = s.length() - 1; i >= 0; i--) {
result = result + s.charAt(i); // builds a brand new String every time
}
return result;
}

So why is it not good enough? Because of immutability. result = result + s.charAt(i) cannot add a character to the existing String. Java has to make a brand new String, copy every character already in result into it, and then write the new character. The old String is thrown away. The picture shows what that means on our five letters.

Count the characters written. The first step writes 1, the second 2, the third 3, then 4 and 5, which is 15 in all, three times the length of the word. For a string of length n it is 1 + 2 + ... + n, which is about n times n over 2. The time is therefore O(n^2), read as order n squared. For a string of 100,000 characters that is about five billion character copies, enough to make a test time out.

The waste is easy to point at now. The o is copied five times, once for every character added after it, yet it only needs to move once, straight to its final place. That is the observation that leads to the better method. A recursive version built on substring has exactly the same quadratic copying, so it is no escape.

4Swapping from both ends, one step at a time

We want every character to move once, directly to its mirror position. A String cannot be changed, so the first step is to copy it into something that can: s.toCharArray() gives us a new char array with the same characters. This is like taking the books off a glass-fronted cabinet and laying them on an open shelf where we can move them.

Now we place one index, left, at 0 and another, right, at the last index. The character at left belongs where right is, and the one at right belongs where left is, so we swap them. Then we move left one step to the right and right one step to the left, and repeat.

Here is the question every beginner asks. To swap, why can we not simply write chars[left] = chars[right] and then chars[right] = chars[left]? Let us try it and see what we lose. With left at 0 and right at 4, the first line writes o into index 0. The h is now gone. The second line copies index 0 into index 4, but index 0 already holds o, so both ends end up as o. The cure is the same as holding one book in your hand while you move the other. We save the left character in a spare variable, tmp, first, then write the right character over it, and then write tmp into the right position.

When should the loop stop? While left < right there is a pair of distinct positions to swap. For an odd length like hello, the indexes meet on the middle character, left == right, and the middle stays where it is. For an even length like abcd, they cross: after swapping indexes 1 and 2, left becomes 2 and right becomes 1. Either way, every mirror pair has been swapped exactly once, using n / 2 swaps. A tempting slip is to write left <= right, which is harmless but wastes a swap of the middle with itself, or to loop over the whole array, which swaps every pair twice and puts the string back the way it was.

Finally new String(chars) turns the array back into a String. If we only need to print, an even simpler loop prints charAt(i) from the last index down to 0 and builds nothing at all.

5Watching the swaps on hello

The picture follows the method on hello. The first swap is shown slowly, one line of code per frame, so you can see why the spare variable is needed. After that, a whole swap and move fit in one frame. The panel shows left, right, tmp and the array.

Step throughReversing hello by swapping from both ends

The two characters about to trade places are marked, the cell just written is highlighted, and positions that are finished are shown as done.

  1. h0e1l2l3o4leftright
    left
    0
    right
    4
    tmp
    -
    array
    h e l l o

    1We copy hello into a char array. left starts at index 0 and right at the last index, 4. Since 0 < 4, the loop begins.

  2. h0e1l2l3o4leftright
    left
    0
    right
    4
    tmp
    h
    array
    h e l l o

    2tmp = chars[left] puts the h aside in a spare variable, like holding one book in your hand. The array has not changed yet.

  3. o0e1l2l3o4leftright
    left
    0
    right
    4
    tmp
    h
    array
    o e l l o

    3chars[left] = chars[right] writes o into index 0. For a moment there are two o's and no h in the array, which is why tmp was needed.

  4. o0e1l2l3h4leftright
    left
    0
    right
    4
    tmp
    h
    array
    o e l l h

    4chars[right] = tmp writes the saved h into index 4. The first pair has traded places: o e l l h.

  5. o0e1l2l3h4leftright
    left
    1
    right
    3
    tmp
    h
    array
    o e l l h

    5left++ and right-- move both pointers one step towards the middle, to 1 and 3. Indexes 0 and 4 are finished.

  6. o0l1l2e3h4leftright
    left
    2
    right
    2
    tmp
    e
    array
    o l l e h

    61 < 3, so the loop swaps the e and the l by the same three lines, then moves the pointers to 2 and 2.

  7. o0l1l2e3h4leftright
    left
    2
    right
    2
    tmp
    -
    array
    o l l e h

    7left < right is now 2 < 2, which is false, so the loop stops. The middle l is its own mirror, and new String(chars) gives olleh.

Let us read the third frame again, because it is the heart of the matter. Just after chars[left] = chars[right], the array reads o, e, l, l, o. The h exists only in tmp. If we had not saved it, it would be lost for good, which is exactly the mistake we tried by hand.

In the sixth frame the second swap happens in one go, and both pointers land on index 2. The last frame shows the loop test 2 < 2 failing. The middle l was never touched, which is correct, because it is already in its mirror position. Two swaps and seven small steps reversed the word.

6The complete Java program

Here is the full class. It has the swap method, a printing loop for the literal reading of the question, and a main that runs our example, an even length string, the empty string, one character, null and the printing loop.

Java
public class ReverseString {
// Swap characters from both ends towards the middle.
static String reverse(String s) {
if (s == null) return null;
char[] chars = s.toCharArray(); // a copy we are allowed to change
int left = 0, right = chars.length - 1;
while (left < right) {
char tmp = chars[left]; // keep the left character safe
chars[left] = chars[right];
chars[right] = tmp;
left++;
right--;
}
return new String(chars);
}
// Print the characters one by one, last first, without building a new string.
static void printReversed(String s) {
for (int i = s.length() - 1; i >= 0; i--) {
System.out.print(s.charAt(i));
}
System.out.println();
}
public static void main(String[] args) {
System.out.println(reverse("hello")); // olleh
System.out.println(reverse("abcd")); // dcba
System.out.println("[" + reverse("") + "]"); // []
System.out.println(reverse("a")); // a
System.out.println(reverse(null)); // null
printReversed("Java 21"); // 12 avaJ
}
}

Let us read reverse in the order it runs. The first line checks for null and returns null, so a null input never reaches toCharArray, which would throw a NullPointerException. Then chars receives a copy of the characters, and left and right are set to the two ends. For the empty string, right is -1, and for one character it is 0.

The while loop runs while left < right. Inside, the three lines are the swap through tmp, in the order we worked out: save the left character, write the right character over it, write the saved one on the right. Then left++ and right-- step both indexes inwards.

When the loop ends, return new String(chars) builds the answer from the array. main prints olleh for hello and dcba for abcd, where the pointers crossed instead of meeting. The empty string prints as [] between brackets, so we can see there is nothing inside, and the single a comes back as a, because 0 < 0 is false and the loop never runs.

printReversed walks from the last index down to 0 and prints each character with print, which does not end the line, and then calls println once to finish the line. For Java 21 it prints 12 avaJ. Notice that the space is a character like any other and is reversed too.

7How much it costs, and the cases at the edges

Let us count on hello first. toCharArray copied 5 characters, the loop did 2 swaps of three assignments each, and new String copied 5 characters again. Every part grows in step with n, so the time is O(n). Compare that with the 15 characters written by concatenation for the same word, a gap that grows quickly with length.

The char array holds n characters, so the extra space is O(n). We cannot avoid that for a String, because the answer is a new String of length n anyway. When people say reverse in place, they mean reversing a char array that the caller already owns, and our loop does that with O(1) extra space, the two indexes and tmp.

Comparing the ways to reverse a string
ApproachTimeExtra space
Concatenation with + in a loop (brute force)O(n^2)O(n) live, O(n^2) written
Recursion with substringO(n^2)O(n^2) copies, O(n) stack
Two pointer swap on a char arrayO(n)O(n) for the array

The usual edge cases need no special code beyond the null check. The empty string and a single character skip the loop, and a palindrome such as racecar comes back unchanged, which makes it a good test.

The edge case that separates a careful answer from a quick one is emoji. A Java char holds 16 bits, and characters outside the basic range, such as most emoji, are stored as two chars together, called a surrogate pair. Our swap reverses those two halves and produces broken text. StringBuilder.reverse() is documented to keep surrogate pairs together, so for real user text the honest production answer is new StringBuilder(s).reverse().toString(), while the two pointer loop answers the algorithm question.

8Follow-up questions

Why not just use StringBuilder.reverse()?

In production code we should, because it runs in O(n), is well tested and keeps surrogate pairs together. In an interview the question is usually there to see whether we can write the loop ourselves. A good way to answer is to mention the library call first, then offer to write the two pointer version and explain it. That shows we know the practical answer and the idea underneath.

How would you check whether a string is a palindrome with the same idea?

A palindrome reads the same in both directions, like racecar. We use the same two indexes from both ends, but compare instead of swapping. While left < right, if charAt(left) differs from charAt(right), we return false; otherwise we move both inwards. If the loop finishes, every mirror pair matched, so we return true. It is O(n) time and O(1) space, and needs no copy at all, because we only read the string.

Could you reverse the string with recursion?

Yes. The reverse of a string is the reverse of everything after its first character, followed by that first character, and the empty string is its own reverse. Written with substring, each call copies most of the string again, so it is O(n^2), and it makes one call per character, so a long string can cause a StackOverflowError. A recursive helper that swaps the two ends of a char array and calls itself on the inner part avoids the copying, but still uses O(n) stack, so the loop remains the better answer.

9Conclusion

We reversed a string by copying it into a char array and swapping characters from both ends towards the middle, holding one character in a spare variable during each swap. Every character moves once, so it takes O(n) time and the O(n) space a new string needs anyway, while concatenation in a loop copies the same characters again and again and costs O(n^2). The clue to remember is that position i must trade places with its mirror n - 1 - i: two pointers from both ends do that in one pass.

What to say in the interviewAbout 90 seconds aloud

Open with

Let me confirm what you want: a method that returns the reversed string, where null returns null and the empty string returns empty. The simplest idea walks backwards and builds the result with plus, but a Java String is immutable, so each plus copies everything built so far, which is O(n squared) in total.

Then, if they want more

Reversing pairs index i with its mirror, n minus one minus i, which is the two pointers from both ends shape.

So I copy the string into a char array with toCharArray, set left to zero and right to the last index, and while left is less than right I swap the two characters through a temporary variable and move both indexes inwards. The temporary is needed because writing the right character over the left one would otherwise lose it.

For hello, the first swap gives oellh and the second gives olleh, and the middle l stays where it is. Then I return new String of the array. That is O(n) time with n over two swaps, and O(n) space for the array, which I need anyway because the result is a new string.

Empty and single character inputs simply skip the loop. In production I would use StringBuilder reverse, because it also keeps emoji, stored as surrogate pairs, in one piece.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 45 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a program that outputs a string's characters in reverse order.": https://scrivio-interview-library.netlify.app/data-structures/solutions/write-a-program-that-outputs-a-string-s-characters-in-reverse-or-8f3819/