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.
- parts
- [d]
Start at the last index. Collect 'd' in a list; we won't glue strings together yet.
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.
parts = []
for i in range(len(s) - 1, -1, -1):
parts.append(s[i])
return "".join(parts)