π·οΈ Category: Strings | π― Difficulty:
Easy| π₯ Frequency: β β β β β
π Problem Statement
Write a function that takes a string and returns it reversed.
π₯ Input β "hello" π€ Output β "olleh"
π₯ Input β "Python" π€ Output β "nohtyP"
π₯ Input β "abcde" π€ Output β "edcba"
π§ What the Interviewer is Testing
| Concept | Why It Matters |
|---|---|
| Python string slicing | Core Python knowledge |
| String immutability | Shows depth of understanding |
| Pythonic thinking | Clean code vs verbose loop |
β οΈ Key fact: Strings in Python are immutable β you cannot reverse them in place. You must return a new string.
π‘ Approach
Use Pythonβs slice notation s[::-1]
- Start from end of string
- Step backwards byΒ
-1 - Returns a brand new reversed string β
β Optimal Solution
def reverse_string(s: str) -> str:
# Slice with step -1 reverses the string
return s[::-1]
# ββ Test Cases βββββββββββββββββββββββββββββββββ
print(reverse_string("hello")) # β
"olleh"
print(reverse_string("Python")) # β
"nohtyP"
print(reverse_string("")) # β
""
print(reverse_string("a")) # β
"a"
π Alternative Approaches
# Using reversed() + join
def reverse_string_v2(s: str) -> str:
return ''.join(reversed(s))
# Using a loop (verbose β avoid in interviews)
def reverse_string_v3(s: str) -> str:
result = ''
for char in s:
result = char + result
return result
π Complexity Analysis
βββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β Time O(n) β Must visit each character once β
β Space O(n) β New string is created in memory β
βββββββββββββββ΄βββββββββββββββββββββββββββββββββββββ
π€ How to Explain in the Interview
βStrings in Python are immutable so I canβt reverse in place. The cleanest approach is slice notation
s[::-1]where-1step means we start from the end and move backwards. This runs in O(n) time and O(n) space.β
π Common Follow-up Questions
Q1 β Can you do it without slicing?
return ''.join(reversed(s))
Q2 β What if input is None?
if not s:
return s
return s[::-1]
Q3 β Reverse words in a sentence?
def reverse_words(s: str) -> str:
return ' '.join(s.split()[::-1])
# "Hello World Python" β "Python World Hello"
π Set 1 of 4 β Python Interview Prep Series β devprepguide.com
