🐍1.5write to reverse the string different way
6 Ways to Reverse a String in Python
Reversing a string is a common coding interview question. Let's explore six different methods to reverse a string in Python, including their explanations, step-by-step breakdowns, and dry runs.
✅ 1. Using Slicing ([::-1]
)
def reverse_string(s):
return s[::-1]
# Example
s = "Python"
print(reverse_string(s)) # Output: "nohtyP"
📝 Explanation
s[::-1]
uses Python's slicing technique.- The slicing syntax is:
s[start:end:step]
.start
: Default (0)end
: Default (end of string)step
:-1
(moves backwards)
🛠 Dry Run
Index | Character | Action |
---|---|---|
5 |
n |
First character in reversed string |
4 |
o |
Next character |
3 |
h |
Next character |
2 |
t |
Next character |
1 |
y |
Next character |
0 |
P |
Last character |
Final output: "nohtyP" ✅
✅ 2. Using reversed()
and join()
def reverse_string(s):
return "".join(reversed(s))
# Example
s = "Python"
print(reverse_string(s)) # Output: "nohtyP"
📝 Explanation
reversed(s)
creates an iterator that iterates over characters in reverse order."".join(...)
combines them into a single string.
🛠 Dry Run
reversed("Python")
→['n', 'o', 'h', 't', 'y', 'P']
"".join(['n', 'o', 'h', 't', 'y', 'P'])
→ "nohtyP"
Final output: "nohtyP" ✅
✅ 3. Using a Loop
def reverse_string(s):
rev = ""
for char in s:
rev = char + rev
return rev
# Example
s = "Python"
print(reverse_string(s)) # Output: "nohtyP"
📝 Explanation
- Initialize
rev = ""
(empty string). - Iterate through each character in
s
. - Add each character to the beginning of
rev
.
🛠 Dry Run
Step | char |
rev (Updated Value) |
---|---|---|
1 | P |
"P" |
2 | y |
"yP" |
3 | t |
"tyP" |
4 | h |
"htyP" |
5 | o |
"ohtyP" |
6 | n |
"nohtyP" |
Final output: "nohtyP" ✅
✅ 4. Using a while
Loop
def reverse_string(s):
rev = ""
i = len(s) - 1
while i >= 0:
rev += s[i]
i -= 1
return rev
# Example
s = "Python"
print(reverse_string(s)) # Output: "nohtyP"
🛠 Dry Run
Step | i (Index) |
s[i] (Character) |
rev (Updated Value) |
---|---|---|---|
1 | 5 |
"n" | "n" |
2 | 4 |
"o" | "no" |
3 | 3 |
"h" | "noh" |
4 | 2 |
"t" | "noht" |
5 | 1 |
"y" | "nohty" |
6 | 0 |
"P" | "nohtyP" |
Final output: "nohtyP" ✅
✅ 5. Using Recursion
def reverse_string(s):
if len(s) == 0:
return s
return s[-1] + reverse_string(s[:-1])
# Example
s = "Python"
print(reverse_string(s)) # Output: "nohtyP"
✅ 6. Using Stack (list
)
def reverse_string(s):
stack = list(s) # Convert string to list
rev = ""
while stack:
rev += stack.pop() # Remove last element
return rev
# Example
s = "Python"
print(reverse_string(s)) # Output: "nohtyP"
🔍 Comparison Table
Method | Code Logic | Time Complexity |
---|---|---|
Slicing ([::-1] ) |
s[::-1] |
O(n) |
reversed() + join() |
"".join(reversed(s)) |
O(n) |
For Loop | Iterates through string, prepending each character | O(n^2) |
While Loop | Iterates backward using an index | O(n) |
Recursion | Calls itself with a smaller substring | O(n) (but high memory usage) |
Stack (list.pop() ) |
Uses a stack (list) to store and pop characters | O(n) |
This table summarizes the different methods with their logic and time complexity. 🚀
Comments
Post a Comment