Browse curriculum

Basics of Strings

A string is a sequence of characters stored as ASCII codes, with basic operations such as reversal.

5 CHARS · 2 SWAPS

SWAP

L

H

0

e

1

l

2

l

3

R

o

4

 

Start with one pointer at each end. Only 2 swaps are needed — each one puts two characters in their final place.

Next

Swap 'H' at 0 with 'o' at 4. Both are now where they belong.

String

Intuition

Strings are sequences of characters. In many languages, they are immutable (cannot be changed in place). Reversing a string typically involves swapping characters from both ends moving towards the center.

Concept

  • ASCII: Each character is stored as a number (e.g., 'A' = 65, 'a' = 97).
  • Immutability: In Java/Python, strings are immutable. Modifying them creates a new string. In C++, they are mutable.
  • Reversal: Use two pointers (start and end) and swap until they meet.

How it Works

Reversal Algorithm:

  1. Initialize L = 0, R = n - 1.
  2. While L < R:
  3. Swap str[L] and str[R].
  4. L++, R--.

Step-by-Step Breakdown

Watch the visualization:

  • See the ASCII values for each character.
  • Watch the characters swap positions during reversal.

When to Use

  • Basic text processing.
  • Checking for palindromes.

When NOT to Use

  • N/A (Fundamental concept).

How to Identify

"Reverse string", "ASCII value", "Character manipulation".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

What does string immutability change in practice?

In Java, Python, JavaScript and C# a string cannot be edited in place, so every modification allocates a new one. Building a string by repeated concatenation in a loop is therefore O(N²); collect the pieces and join once instead.


How do I reverse a string in place?

Only in a language with mutable strings, such as C or C++. Swap the characters at two pointers walking inward until they meet, which is O(N) time and O(1) extra space.


Why do characters behave like numbers?

Each character is stored as an integer code, so in ASCII the letter A is 65 and the letter a is 97. That is what lets you index a frequency table by subtracting the code of a from the character.