Interview Q&A / Python

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

Write a function that reverses a string in Python.

SHORT ANSWER

The shortest way is slicing with a negative step: s[::-1]. You can also use "".join(reversed(s)). Both build a new string in O(n) time, since strings cannot be changed in place.

Explain it simply

Slicing has the form s[start:stop:step]. Leaving start and stop empty and using step -1 walks the string from the last character to the first.

Line by line

python
def reverse_string(s):
    return s[::-1]

def reverse_with_join(s):
    return "".join(reversed(s))

def reverse_manual(s):
    result = []
    for ch in s:
        result.insert(0, ch)   # slow: O(n) each time
    return "".join(result)

print(reverse_string("placement"))     # Output: tnemecalp
print(reverse_with_join("python"))     # Output: nohtyp
print(reverse_string("a"))             # Output: a

reversed(s) returns an iterator, so join is needed to get a string back. The manual version works but insert(0, ...) shifts every element each time, making it O(n squared).

Complexity

Time O(n), space O(n) for the new string (the manual insert version is O(n squared) time).

What to say in the interview

"I'd use s[::-1], which is idiomatic and fast. If the interviewer wants no slicing, I loop and build a list, then join it. I avoid repeated string concatenation or insert(0) because they are quadratic."

Common mistakes

  • Trying s.reverse(). Strings have no such method; it belongs to lists.

#python#strings#coding

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.