AlgoTales · Roadmap

String reversal

Beginner · 6 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Reversing a string means swapping the first and last characters, then the second and second-last, until you reach the middle. The same two-ended swap shows up in many other tasks, such as undoing steps, flipping lists, and doing sums on very long numbers typed as text.

Practical use cases

  • Web app: Adding two very long numbers typed as text. A calculator page lets users add numbers with hundreds of digits, which no ordinary number type can hold. The code reverses both strings so the units digit comes first, adds digit by digit with a carry, and reverses the answer back. The sum is correct to the last digit.
  • Web app: Adding commas to a big price. A shop page must show 1234567 as 1,234,567. Commas are counted from the right, so the code reverses the digits, inserts a comma after every third one, and reverses the result back. The price becomes easy to read without any awkward index maths from the left.
  • System: Undo stacks and interview warm-ups. An editor undo list is a pile where the last action is undone first, which is a reversal of order. Reversing a string is also the classic warm-up question because it teaches the two-ended swap used in harder problems. Once you can reverse in place with two markers, harder problems such as rotating arrays and checking palindromes feel familiar.

The story: The Mirror Writer

Mira had read that Leonardo da Vinci wrote in mirror writing, and she wanted to try it. She chose the word NAMASTE and began copying it letter by letter from the end onto a fresh sheet: E, T, S, A, M, A, N. It worked, but she needed a whole new page for every word.

"Waste of paper," said Kabir. "Why not fix the word right where it sits?" He pointed at the first letter and the last letter. "Swap them. Now the second and the second-last. Keep going until your fingers meet."

N and E traded places. Then A and T. Then M and S. The lonely A in the middle had no one to swap with and did not need to move. The word flipped without any extra page, and the whole job took only three quick swaps. Swapping from both ends toward the middle is the classic way to reverse a string.

How to spot this problem, and where you need it

You need text, digits or items in the opposite order, such as the last step first, or you must process digits from the right, and index juggling keeps causing bugs.

Signs you need it

  • The problem says reverse, flip, mirror, or process from the least significant digit.
  • You are handling very long numbers as strings, and addition or multiplication must start at the end.
  • Your code builds a reversed copy character by character, using a lot of memory for large texts.

Where to use it in a project

  • Big-number calculators and tools that process numbers typed as text, such as invoice totals with huge values.
  • Undo and history features, display of right-to-left languages, and palindrome or mirror checks.

The solution

Place one marker at the start and one at the end. Swap the two characters they point to, then move the markers one step towards each other. Stop when they meet in the middle. In languages where strings cannot be changed in place, first split the text into an array of characters, do the swaps, and join it back together. Each character is moved once.

Payoff: Before: awkward index maths and an extra copy. After: a simple swap loop that finishes in half a pass.

Explain it like I am 8

Line up kids in a row, each holding a letter card. Ask the first and last kid to swap places, then the second and the second-last, and so on, until everybody has met their partner. The whole row is now backwards.

How it works, step by step

  1. Put one pointer at each end: left = 0, right = length - 1.
  2. Swap the two letters they point to.
  3. Move inward: left++, right--.
  4. Stop when left reaches or passes right. The middle letter of an odd word stays put.
  5. Remember strings may be fixed. In JavaScript you cannot change a string in place, so you first turn it into an array of letters.

The code in four languages

PHP

<?php
// Reverse a string by swapping from both ends.
function reverseString(string $s): string {
    $chars = str_split($s);                  // letters in an array
    $left = 0;
    $right = count($chars) - 1;
    while ($left < $right) {
        $tmp = $chars[$left];                // swap the two ends
        $chars[$left] = $chars[$right];
        $chars[$right] = $tmp;
        $left++;
        $right--;
    }
    return implode('', $chars);
}

// Bonus: reverse the ORDER OF WORDS, keeping each word as it is.
function reverseWords(string $sentence): string {
    return implode(' ', array_reverse(explode(' ', $sentence)));
}

echo reverseString("NAMASTE") . "\n";            // ETSAMAN
echo reverseWords("chai pe charcha") . "\n";     // charcha pe chai

JavaScript

// Reverse a string by swapping from both ends.
function reverseString(s) {
  const chars = s.split('');                 // strings are fixed: use an array
  let left = 0;
  let right = chars.length - 1;
  while (left < right) {
    const tmp = chars[left];                 // swap the two ends
    chars[left] = chars[right];
    chars[right] = tmp;
    left++;
    right--;
  }
  return chars.join('');
}

// Bonus: reverse the ORDER OF WORDS, keeping each word as it is.
function reverseWords(sentence) {
  return sentence.split(' ').reverse().join(' ');
}

console.log(reverseString('NAMASTE'));            // ETSAMAN
console.log(reverseWords('chai pe charcha'));     // charcha pe chai

Java

import java.util.*;

public class Main {
    // Reverse a string by swapping from both ends.
    static String reverseString(String s) {
        char[] chars = s.toCharArray();          // strings are fixed: use an array
        int left = 0;
        int right = chars.length - 1;
        while (left < right) {
            char tmp = chars[left];              // swap the two ends
            chars[left] = chars[right];
            chars[right] = tmp;
            left++;
            right--;
        }
        return new String(chars);
    }

    // Bonus: reverse the ORDER OF WORDS, keeping each word as it is.
    static String reverseWords(String sentence) {
        List<String> words = Arrays.asList(sentence.split(" "));
        Collections.reverse(words);
        return String.join(" ", words);
    }

    public static void main(String[] args) {
        System.out.println(reverseString("NAMASTE"));            // ETSAMAN
        System.out.println(reverseWords("chai pe charcha"));     // charcha pe chai
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// reverseString reverses a string by swapping from both ends.
func reverseString(s string) string {
	chars := []rune(s) // strings are fixed: use a slice of letters
	left, right := 0, len(chars)-1
	for left < right {
		chars[left], chars[right] = chars[right], chars[left] // swap the two ends
		left++
		right--
	}
	return string(chars)
}

// reverseWords reverses the ORDER OF WORDS, keeping each word as it is.
func reverseWords(sentence string) string {
	words := strings.Split(sentence, " ")
	for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
		words[i], words[j] = words[j], words[i]
	}
	return strings.Join(words, " ")
}

func main() {
	fmt.Println(reverseString("NAMASTE"))        // ETSAMAN
	fmt.Println(reverseWords("chai pe charcha")) // charcha pe chai
}

Time: O(n) · Extra space: O(n). About n/2 swaps. We hold a copy of the letters because strings cannot be edited in place in most languages.

Watch out for

  • Swapping all the way to the end (left < length) instead of stopping in the middle. That swaps everything twice and undoes your work.
  • Trying s[0] = 'X' on a JavaScript string. It silently does nothing; convert to an array first.

Quick check

  1. How many swaps reverse a 7-letter word?
    • 7
    • 3
    • 4
  2. What happens if you keep swapping past the middle?
    • Nothing, it is faster
    • The word is sorted
    • You undo your own work
  3. Reversing the words of "chai pe charcha" gives…
    • charcha pe chai
    • ahcrahc ep iahc
    • chai charcha pe