Animations
Reverse a String — Visual Walkthrough
Watch how each character gets prepended to the front of the result, building the reversed string step by step.
Reverse a String
Input: "PYTHON"
Loop through every character and add it to the front of the result. The first character ends up last — the last character ends up first.
Reverse Stringprepend · O(n)
inputPYTHON
Input string
P
[0]Y
[1]T
[2]H
[3]O
[4]N
[5]result (building from front)
0 / 6 charsempty string ""
reverse_string.py
def reverse_string(s):
result = ""
for char in s:
# pick current character
result = char + result # prepend
return result
Call reverse_string("PYTHON")
step 0/15
0%
How it works
def reverse_string(s):
result = ""
for char in s:
result = char + result # prepend to front
return resultEach iteration — the new character goes to the front, pushing everything already in result one position to the right.
| Step | char | result |
|---|---|---|
| 1 | P | "P" |
| 2 | Y | "YP" |
| 3 | T | "TYP" |
| 4 | H | "HTYP" |
| 5 | O | "OHTYP" |
| 6 | N | "NOHTYP" |
The cleanest Python solution is s[::-1] — slice with step -1. The loop version shown here is more useful for understanding what reversal actually does step by step.
Complexity
| Time | Space | |
|---|---|---|
| This approach | O(n) | O(n) |