JUNE 2026 Coding interviews test recall. kodr.run tests engineering judgment
PythonIntermediate25 minGeneral

Top Python Coding Interview Questions (With Answers)

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:

LayerWhat a weaker answer doesWhat a stronger answer does
CorrectnessSolves the happy path; misses empty input, duplicates, or caseNames the edge cases before coding and handles them
EfficiencyShips the first idea that works, usually a nested loopStates the complexity, then reaches for the O(n) approach and explains why
IdiomReimplements built-ins by handUses Counter, slicing, comprehensions, and explains the memory trade-off
CommunicationCodes in silence, presents a finished blockThinks 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.

Python · reverse_string.py
text = "interview"
reversed_text = text[::-1]
print(reversed_text) # weivretni

The 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:

Python · reverse_string.py
reversed_text = "".join(reversed(text)) # weivretni

Evaluates: 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?

Python · palindrome.py
def is_palindrome(text):
    cleaned = text.lower().replace(" ", "")
    return cleaned == cleaned[::-1]


print(is_palindrome("Race car")) # True
print(is_palindrome("hello")) # False

The 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?

Python · count_vowels.py
def count_vowels(text):
    return sum(1 for ch in text.lower() if ch in "aeiou")


print(count_vowels("Education")) # 5

The 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.

ApproachMemoryWhen it matters
sum(1 for ...) (generator)O(1) extraLarge strings; preferred
sum([1 for ...]) (list comp)O(n) extraSame 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?

Python · non_repeating_char.py
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")) # w

Two 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?

Python · check_anagram.py
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")) # False

Comparing two Counter objects checks character frequencies in O(n). The taught alternative sorts both:

Python
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, comparessorted(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

Python · fizzbuzz.py
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 FizzBuzz

The trap: check i % 15 first. Evaluates: correctness and ordering of conditions.

7Fibonacci sequence

Python · fibonacci.py
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

Python · remove_dupes.py
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

Python · most_freq.py
from collections import Counter


def max_char(text):
    return Counter(text).most_common(1)[0][0]


print(max_char("aabbbcc")) # b

Evaluates: idiom. Knowing Counter.most_common rather than hand-rolling.

10Two Sum

Python · two_sum.py
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

Python · missing_num.py
def missing(nums, n):
    expected = n * (n + 1) // 2
    return expected - sum(nums)


print(missing([1, 2, 4, 5], 5)) # 3

O(n) time, O(1) space. Evaluates: reaching for the maths insight over sorting.

12Reverse words in a sentence

Python · reverse_words.py
sentence = "the quick brown fox"
result = " ".join(sentence.split()[::-1])
print(result) # fox brown quick the

Reverses word order, not characters. Evaluates: correctness. Clarifying "words" versus "string" up front.

13Balanced parentheses

Python · balanced_parentheses.py
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("([)]")) # False

O(n). Evaluates: data-structure choice. Recognising the stack signature.

14Flatten a nested list

Python · flatten_nested.py
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

Python · word_freq.py
from collections import Counter


text = "the cat sat on the mat the cat"
freq = Counter(text.split())
print(freq["the"]) # 3
print(freq["cat"]) # 2

Evaluates: idiom. Reusing Counter across problem shapes.

How should you prepare for a Python coding interview?

  1. Type them out, don't read them. Muscle memory frees attention for the actual problem. Run each, change inputs, break and fix.
  2. Say the complexity out loud. Practise the one-sentence trade-off. That sentence is what most of these questions test.
  3. 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.