Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

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)