Why interviewers still ask this
If you are preparing for a Python interview, the same handful of questions appear again and again across service companies, product firms, and campus placements. This guide collects the fifteen that come up most, grouped by the kind of thinking each one tests. For every question you get working code, the output it produces, the time and space complexity, and, because the people setting these questions read guides too, a short note on what a strong answer actually signals.
The first five are covered in depth, including the optimised alternative an interviewer is usually steering you toward. The remaining ten are tighter: the working solution and the one insight that matters.
How interviewers read a Python answer
When an interviewer poses a coding question, they are reading four layers, roughly in this order:
| Layer | What a weaker answer does | What a stronger answer does |
| Correctness | Solves the happy path; misses empty input, duplicates, or case | Names the edge cases before coding and handles them |
| Efficiency | Ships the first idea that works, usually a nested loop | States the complexity, then reaches for the O(n) approach and explains why |
| Idiom | Reimplements built-ins by hand | Uses Counter, slicing, comprehensions, and explains the memory trade-off |
| Communication | Codes in silence, presents a finished block | Thinks out loud, so the interviewer sees the reasoning |
1How do you reverse a string in Python?
The classic opener. It reveals whether you reach for Python's idioms or reimplement them.
text = "interview"
reversed_text = text[::-1]
print(reversed_text) # weivretniThe slice [::-1] walks the string end to start with a step of −1. O(n) time, O(n) space. Alternative that works on any iterable:
reversed_text = "".join(reversed(text)) # weivretniEvaluates: idiom. Reaching for [::-1] signals comfort with Python. A manual loop signals someone who hasn't absorbed Python's conventions yet.
2How do you check whether a string is a palindrome?
def is_palindrome(text):
cleaned = text.lower().replace(" ", "")
return cleaned == cleaned[::-1]
print(is_palindrome("Race car")) # True
print(is_palindrome("hello")) # FalseThe judgment is in the cleaning step. A strong candidate asks whether case and spaces should be ignored before coding. O(n) time, O(n) space.
Evaluates: correctness and edge-case awareness. The clarifying question is worth more than the code.
3How do you count the vowels in a string?
def count_vowels(text):
return sum(1 for ch in text.lower() if ch in "aeiou")
print(count_vowels("Education")) # 5The generator expression is consumed by sum without building a list. The list-comp form sum([...]) gives the same answer but materialises the whole list first.
| Approach | Memory | When it matters |
sum(1 for ...) (generator) | O(1) extra | Large strings; preferred |
sum([1 for ...]) (list comp) | O(n) extra | Same result, wastes memory |
Evaluates: idiom and memory. The follow-up question, "what if the string is a gigabyte?", is where the generator answer shows you understand lazy evaluation.
4How do you find the first non-repeating character in a string?
from collections import Counter
def first_unique(text):
counts = Counter(text)
for ch in text:
if counts[ch] == 1:
return ch
return None
print(first_unique("swiss")) # wTwo passes, O(n) total. The naive version counts inside the loop: text.count(ch) rescans every iteration, making it O(n²).
Evaluates: efficiency. Both return "w". The signal is noticing the hidden O(n²) and reaching for Counter to make it O(n), said out loud.
5How 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")) # FalseComparing two Counter objects checks character frequencies in O(n). The taught alternative sorts both:
def is_anagram_sorted(a, b):
return sorted(a) == sorted(b) # correct, but O(n log n)Counter(a) == Counter(b) | O(n) | Counts once, compares | sorted(a) == sorted(b) | O(n log n) | Shorter, slower at scale |
Evaluates: efficiency and idiom. Naming the trade-off unprompted, "sorted works and is O(n log n), but Counter gets it to O(n)", is the senior signal.
6FizzBuzz
for i in range(1, 16):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
# 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzzThe trap: check i % 15 first. Evaluates: correctness and ordering of conditions.
7Fibonacci sequence
def fib(n):
a, b = 0, 1
result = []
for _ in range(n):
result.append(a)
a, b = b, a + b
return result
print(fib(8)) # [0, 1, 1, 2, 3, 5, 8, 13]a, b = b, a + b is the Pythonic move. Iterative O(n) versus naive recursion O(2ⁿ). Evaluates: idiom and avoiding exponential recursion.
8Remove duplicates, keep order
def dedupe(seq):
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))]
print(dedupe([3, 1, 3, 2, 1, 5])) # [3, 1, 2, 5]Set lookups are O(1), so O(n) overall. Evaluates: efficiency. (Cleaner production answer: list(dict.fromkeys(seq)).)
9Most frequent character
from collections import Counter
def max_char(text):
return Counter(text).most_common(1)[0][0]
print(max_char("aabbbcc")) # bEvaluates: idiom. Knowing Counter.most_common rather than hand-rolling.
10Two Sum
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = i
return []
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]Hashmap, one pass, O(n). Brute force is O(n²). Evaluates: efficiency. The canonical O(n²) to O(n) shift using a hashmap.
11Missing number from 1 to n
def missing(nums, n):
expected = n * (n + 1) // 2
return expected - sum(nums)
print(missing([1, 2, 4, 5], 5)) # 3O(n) time, O(1) space. Evaluates: reaching for the maths insight over sorting.
12Reverse words in a sentence
sentence = "the quick brown fox"
result = " ".join(sentence.split()[::-1])
print(result) # fox brown quick theReverses word order, not characters. Evaluates: correctness. Clarifying "words" versus "string" up front.
13Balanced parentheses
def balanced(s):
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print(balanced("({[]})")) # True
print(balanced("([)]")) # FalseO(n). Evaluates: data-structure choice. Recognising the stack signature.
14Flatten a nested list
def flatten(nested):
result = []
for item in nested:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
print(flatten([1, [2, [3, 4], 5]])) # [1, 2, 3, 4, 5]Evaluates: recognising that arbitrary nesting needs recursion.
15Word frequency
from collections import Counter
text = "the cat sat on the mat the cat"
freq = Counter(text.split())
print(freq["the"]) # 3
print(freq["cat"]) # 2Evaluates: idiom. Reusing Counter across problem shapes.
How should you prepare for a Python coding interview?
- Type them out, don't read them. Muscle memory frees attention for the actual problem. Run each, change inputs, break and fix.
- Say the complexity out loud. Practise the one-sentence trade-off. That sentence is what most of these questions test.
- Ask before you assume. Half the questions hide an edge case the candidate is meant to surface. Clarifying first beats coding fast.
Frequently asked questions
What are the most common Python coding interview questions? Four groups: string manipulation, counting/frequency (usually collections.Counter), array/number logic (Two Sum, missing number), and structure problems (balanced parentheses, flattening). The fifteen here cover the patterns behind nearly all of them.
Are Python interview questions different for freshers and experienced developers? The questions overlap, but the bar shifts. Freshers need a correct working solution. Experienced candidates are expected to state complexity, reach for the optimised approach, and explain the trade-off.
Should I use built-in functions like Counter in an interview? Yes, and explain why. It signals fluency. The exception is when the interviewer explicitly asks you to implement the logic by hand.
How important is time and space complexity in a Python interview? Often the single most important thing. Naming the complexity of both naive and optimised, unprompted, frequently separates a pass from an offer.
How long does it take to prepare for a Python coding interview? If you know the syntax, a few focused weeks to reproduce the patterns without reference. The goal is pattern recognition, not memorising answers.