Why interviewers still ask this
Strings are the first data type most people learn to manipulate, which makes them a low-friction way to open a technical round. But the questions below are not just warm-ups. A few of them (case conversion without built-ins, custom split, substring search) are used specifically to check whether a candidate understands what Python's string methods are doing underneath, not just whether they can call them.
The first four questions get full treatment: working code, a naive alternative, and the complexity gap between them. The remaining six are tighter: one solution and the insight it tests.
How interviewers read a string-manipulation answer
| Layer | What a weaker answer does | What a stronger answer does |
| Correctness | Handles the example given, breaks on empty strings or mixed case | Names the edge cases (empty input, case sensitivity, whitespace) before coding |
| Efficiency | Rebuilds strings inside a loop with +=, unaware of the cost | Uses join, slicing, or a list buffer, and can explain why string concatenation in a loop is O(n²) |
| Idiom | Reimplements built-ins like upper() or split() from scratch when not asked to | Uses the built-in, and can still explain the manual approach if asked |
| Communication | Presents a finished block without narrating the approach | Talks through the plan before writing code |
1How do you check if two strings are anagrams?
from collections import Counter
def is_anagram(a, b):
return Counter(a) == Counter(b)
print(is_anagram("listen", "silent")) # True
print(is_anagram("hello", "world")) # FalseCounter builds a frequency map of each string in O(n) and compares them in O(1) average case. The commonly taught alternative sorts both strings:
def is_anagram_sorted(a, b):
return sorted(a) == sorted(b) # correct, but O(n log n)Evaluates: efficiency and idiom. Naming that Counter gets you to O(n) while sorting costs O(n log n) is the signal interviewers are listening for.
2How do you reverse the words in a sentence without reversing the letters?
sentence = "the quick brown fox"
result = " ".join(sentence.split()[::-1])
print(result) # fox brown quick theThe trap is assuming this means character reversal. split() breaks the sentence into words, the slice reverses their order, and join reassembles them with spaces.
# Wrong: reverses every character, including within words
wrong = sentence[::-1] # xof nworb kciuq ehtEvaluates: correctness. Clarifying "reverse the words" versus "reverse the string" before coding is worth more than the one-liner itself.
3How do you check if a string is a valid palindrome, ignoring case and spaces?
def is_palindrome(text):
cleaned = "".join(ch.lower() for ch in text if ch.isalnum())
return cleaned == cleaned[::-1]
print(is_palindrome("A man, a plan, a canal: Panama")) # TrueThe naive version checks the raw string directly, which fails on punctuation and case. This version filters to alphanumeric characters first, then compares against its own reverse.
| Approach | Handles punctuation/case | Result on the example |
text == text[::-1] | No | False (incorrect) |
| Cleaned then reversed | Yes | True (correct) |
Evaluates: correctness and edge-case handling. This is one of the most commonly failed string questions, not because the logic is hard, but because candidates skip the cleaning step.
4How do you find the longest word in a sentence?
def longest_word(sentence):
return max(sentence.split(), key=len)
print(longest_word("the quick brown fox jumps")) # quickmax with a key function avoids a manual loop entirely. The manual version tracks a running maximum:
def longest_word_manual(sentence):
words = sentence.split()
longest = ""
for word in words:
if len(word) > len(longest):
longest = word
return longestBoth are O(n). The difference is not speed, it is whether the candidate knows max(..., key=...) exists.
Evaluates: idiom. Either answer is correct, but the one-liner signals more fluency with Python's functional tools.
5How do you count the frequency of each character in a string?
from collections import Counter
text = "programming"
freq = Counter(text)
print(freq) # Counter({'r': 2, 'g': 2, 'm': 2, 'p': 1, 'o': 1, 'a': 1, 'i': 1, 'n': 1})Evaluates: idiom. Reaching for Counter instead of a manual dictionary loop.
6How do you remove all whitespace from a string?
text = " hello world "
result = "".join(text.split())
print(result) # helloworldEvaluates: knowing that split() with no arguments collapses any amount of whitespace, which makes this shorter and more robust than replace(" ", "").
7How do you convert a string to title case without using .title()?
def to_title_case(text):
return " ".join(word[0].upper() + word[1:].lower() for word in text.split())
print(to_title_case("hello WORLD from python")) # Hello World From PythonEvaluates: whether the candidate understands what .title() is doing under the hood. This question is asked specifically to check for that understanding, not to avoid the built-in in production.
8How do you check if one string is a rotation of another?
def is_rotation(s1, s2):
return len(s1) == len(s2) and s2 in s1 + s1
print(is_rotation("waterbottle", "erbottlewat")) # TrueEvaluates: a classic trick question. Concatenating s1 with itself contains every possible rotation of s1 as a substring, which turns an apparently complex problem into a single in check.
9How do you find the first repeated character in a string?
def first_repeated(text):
seen = set()
for ch in text:
if ch in seen:
return ch
seen.add(ch)
return None
print(first_repeated("swiss")) # sEvaluates: using a set for O(1) lookups instead of checking text.count(ch) inside the loop, which would make the solution O(n²).
10How do you check if a string contains only digits?
text = "12345"
print(text.isdigit()) # True
text2 = "123a5"
print(text2.isdigit()) # FalseEvaluates: knowing the built-in exists at all. This one is less about logic and more about library familiarity, interviewers use it to gauge how much of the standard string API a candidate actually knows.
How should you prepare for a string manipulation interview?
- Know which operations are O(n) and which are O(n²). String concatenation with
+=inside a loop is the most common hidden cost.joinand list buffers avoid it. - Practise the manual version of common built-ins.
.title(),.split(), and.reverse()-style operations are sometimes asked "without using the built-in" specifically to test whether you understand the mechanism. - Say the edge case out loud before coding. Empty strings, mixed case, and punctuation are where most string answers actually fail, not in the core logic.
Frequently asked questions
Are string manipulation questions asked at every level, or mostly for freshers? They appear at every level, but the bar changes. Freshers are expected to get a correct answer using built-ins. Experienced candidates are more often asked to explain the built-in's complexity or implement it manually.
Why do interviewers ask you to avoid built-in functions like .title() or .reverse()? Not to test whether you can avoid them in real code, but to check whether you understand what the built-in is doing underneath. It is a comprehension check, not a style preference.
What is the most commonly failed string interview question? Palindrome checks that ignore punctuation and case. Most failures come from skipping the cleaning step, not from the comparison logic itself.
Is string immutability actually relevant to interview answers? Yes. It is the reason += inside a loop is expensive (each concatenation builds a new string) and why join is the preferred approach for building strings incrementally.
Related tutorials: Top Python Coding Interview Questions · Python Data Structures Interview Questions · Python Pattern Programs