DSA Factory
Free lessonsStrings · Stage 0 · Walking a string · Step 2

Building a new string

Build a reversed copy of a string, one character at a time. About 7 minutes.

A string can't be edited, only rebuilt

In Python, Java and JavaScript, once a string is made it can't be changed, like text printed on a page. You can't swap its first letter for another. To "change" a string, you build a new one with the characters you want.

So reversing a string means walking it from the back and building a fresh string as you go.

No editing in place: build a new string instead.
s = "stressed", walking from the back
s
0
t
1
r
2
e
3
s
4
s
5
e
6
d
7
i
parts
[d]

Start at the last index. Collect 'd' in a list; we won't glue strings together yet.

Move 1 of 5

Collect the pieces, glue once

Gluing one character at a time onto a growing string can secretly copy the whole thing on every step. For a long string that gets slow.

The usual fix: collect the characters in a list (Python, JavaScript) or a StringBuilder (Java), and turn them into a string once at the very end. In C++, strings can grow cheaply, so adding one character at a time is fine.

Collect, then join: one copy at the end, not one per step.
In code
parts = []
for i in range(len(s) - 1, -1, -1):
    parts.append(s[i])
return "".join(parts)
Quick check

A loop walks "abc" from the last character to the first, collecting each one. What does it build?

  1. A"cba"
  2. B"abc"
  3. CAn error
Show the answer

"cba". The last character comes first: c, then b, then a.

Your problem

Reverse a string

Return a new string with the characters of s in reverse order.

Example
s = "stressed" → "desserts"

0 ≤ length of s ≤ 10,000 · s has letters, digits and spaces

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding