🏷️ 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

ConceptWhy It Matters
Python string slicingCore Python knowledge
String immutabilityShows depth of understanding
Pythonic thinkingClean 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 -1 step 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

Scroll to Top