/writing/recruiting & ats/python-coding-questions-interview
§ Hiring Tips·17 min read·October 7, 2026

Python Coding Interview Questions: 10 Most Asked, Solved

O
Olibr TeamHiring Tips
Python Coding Interview Questions: 10 Most Asked, Solved

Python Coding Interview Questions: 10 Most Asked, Solved

If you are searching for python coding questions interview panels actually ask, you want real problems with working answers, not theory. This article gives you exactly that. Every question comes with code you can run, and the set covers freshers to experienced candidates.

Here is the short answer. Most Python interviews rely on a small group of patterns: string manipulation, list and dictionary handling, recursion, sorting, and basic complexity analysis. If you can solve reversing a string, finding duplicates, and checking for anagrams without hesitation, you already clear the first technical screen at most companies. Senior rounds add generators, decorators, and optimizing for time and space.

Below are 10 of the most asked Python coding interview questions, each solved step by step. At Olibr, we work with recruiters who screen thousands of developer profiles, so we see which questions separate strong candidates from weak ones. Use this list to practice, or to build a fairer technical screening round for your own hiring team.

1. Check if a string is a palindrome

The question and why interviewers ask it

Given a string, return True if it reads the same forward and backward, ignoring case and punctuation. This is one of the python coding interview questions that opens many screens because it is quick to state and easy to extend. It tests slicing, loops, and whether you think about edge cases before you type.

Test your function against these inputs:

  • An empty string, which should return True
  • "Madam", which mixes uppercase and lowercase
  • "A man, a plan, a canal: Panama", which has spaces and punctuation

Solution with code

Start with the slicing approach. It is short, readable, and the answer most interviewers expect first.

def is_palindrome(s):
    cleaned = "".join(ch.lower() for ch in s if ch.isalnum())
    return cleaned == cleaned[::-1]

print(is_palindrome("A man, a plan, a canal: Panama"))  # True
print(is_palindrome("python"))  # False

Then expect a push for a version without the reversed copy. A two-pointer check compares characters from both ends and stops at the first mismatch.

def is_palindrome_two_pointer(s):
    left, right = 0, len(s) - 1
    while left < right:
        if not s[left].isalnum():
            left += 1
        elif not s[right].isalnum():
            right -= 1
        elif s[left].lower() != s[right].lower():
            return False
        else:
            left += 1
            right -= 1
    return True

How it works and complexity

Here, the first function filters out anything that is not a letter or digit, lowercases the rest, and compares the result with its reversed copy. The second skips junk characters in place, so it needs no extra memory beyond a few integers.

Letter tiles in a row on a tray with a mirror reflecting them reversed.

Clean the input first, then compare, and say your complexity out loud.

Approach Time Space
Slicing O(n) O(n)
Two pointers O(n) O(1)

Follow-up variations

Expect one twist after the basic answer. These are the ones that come up most in python code interview questions and answers lists, so practice them next:

  • Check whether an integer is a palindrome without converting it to a string
  • Find the longest palindromic substring in a given string
  • Return True if the string becomes a palindrome after deleting at most one character

2. Reverse a string

The question and why interviewers ask it

Write a function that takes a string and returns it reversed, so "python" becomes "nohtyp". It shows up in almost every list of python basic coding questions for interview rounds because it is fast to state and fast to check.

Interviewers want to see that you know strings are immutable in Python. They also like to add "no slicing" halfway through, to see how you think without your favorite shortcut.

Solution with code

Give the one-liner first, then show you can build it by hand.

def reverse_slice(s):
    return s[::-1]

def reverse_loop(s):
    chars = []
    for i in range(len(s) - 1, -1, -1):
        chars.append(s[i])
    return "".join(chars)

def reverse_recursive(s):
    if len(s) <= 1:
        return s
    return reverse_recursive(s[1:]) + s[0]

print(reverse_slice("python"))  # nohtyp

For the loop version, append to a list and join once. Concatenating onto a string inside the loop works, but it builds a new string every pass.

How it works and complexity

Slicing with a step of -1 walks the string backward and copies it. The loop does the same by hand, and the recursive version peels off the first character and puts it at the end.

Strings are immutable, so every reversal builds a new string.

Approach Time Space
Slicing O(n) O(n)
Loop with join O(n) O(n)
Recursion O(n^2) O(n) stack

Mention that recursion hits Python's default limit of about 1,000 frames, so it fails on long inputs.

Follow-up variations

These are common in python interview coding questions for freshers, so try them next:

  • Reverse the order of words in a sentence
  • Reverse each word but keep the word order
  • Reverse a list of characters in place using two pointers

3. Print the Fibonacci series up to n terms

The question and why interviewers ask it

Write a function that prints the first n Fibonacci numbers, where each term is the sum of the previous two. For n = 7, the output is 0, 1, 1, 2, 3, 5, 8. It is one of the most asked python coding questions in interview rounds because it tests loops, tuple swapping, and whether you notice the cost of naive recursion. Handle n = 0 and n = 1 before anything else.

Solution with code

Begin with the iterative loop. It is the answer to give first.

def fibonacci(n):
    series = []
    a, b = 0, 1
    for _ in range(n):
        series.append(a)
        a, b = b, a + b
    return series

print(fibonacci(7))  # [0, 1, 1, 2, 3, 5, 8]

Next, show the recursive version and add memoization with lru_cache so it does not recompute the same terms.

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print([fib(i) for i in range(7)])

How it works and complexity

The loop keeps only the last two values and updates both in one line, so no temporary variable is needed. Plain recursion without a cache recalculates the same terms again and again, which is why it grows exponentially.

Naive recursive Fibonacci is O(2^n), and a cache brings it down to O(n).

Approach Time Space
Iterative O(n) O(n) to store the list
Naive recursion O(2^n) O(n) stack
Memoized recursion O(n) O(n)

Follow-up variations

These come up in python interview coding questions for experienced candidates:

  • Write a generator that yields Fibonacci terms lazily
  • Return the nth term in O(log n) using matrix exponentiation
  • Sum the even Fibonacci numbers below 4 million

4. Find the factorial of a number

The question and why interviewers ask it

Compute n!, the product of all positive integers up to n, so 5 gives 120. It appears in most sets of programming interview questions python candidates practice because it tests loops versus recursion in one short problem. Interviewers also check your edge cases: 0! equals 1, and negative input should raise an error.

Solution with code

Give the loop first, then the recursive version.

def factorial(n):
    if n < 0:
        raise ValueError("n must be non-negative")
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

def factorial_recursive(n):
    if n < 0:
        raise ValueError("n must be non-negative")
    if n <= 1:
        return 1
    return n * factorial_recursive(n - 1)

print(factorial(5))  # 120

In real projects, math.factorial is the right call. Still, interviewers expect you to write it by hand before they let you use it.

How it works and complexity

The loop multiplies a running result by each integer from 2 to n. Recursion does the same work, but it stacks one frame per call, so it fails near 1,000 levels with a RecursionError. Python integers have no size limit, so large results stay exact, though each multiplication gets slower as the number grows.

State your base case and the recursion limit before you write a single line.

Approach Time Space
Loop O(n) O(1)
Recursion O(n) O(n) stack
math.factorial O(n) O(1)

Follow-up variations

Expect one of these in python coding interview questions and answers rounds:

  • Count the trailing zeros in n! without computing the factorial
  • Use functools.reduce to write the factorial in one line
  • Compute combinations (nCr) using factorials
  • Add memoization so repeated calls reuse earlier results

5. Remove duplicates from a list

The question and why interviewers ask it

Given a list, return a new list with every duplicate removed. The real test is the follow-up: should the original order survive? This is a staple of python coding questions interview panels because it checks whether you know sets and dictionaries, and whether you ask about order before you type.

Solution with code

Start with the order-preserving version, since it is the safest default. Dicts keep insertion order in Python 3.7 and later, so dict.fromkeys does the job in one line.

def remove_duplicates(items):
    return list(dict.fromkeys(items))

def remove_duplicates_loop(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

print(remove_duplicates([3, 1, 3, 2, 1]))  # [3, 1, 2]
print(list(set([3, 1, 3, 2, 1])))  # order not guaranteed

Plain set() is the shortest answer, but it loses order. Say so out loud. Also note that items must be hashable, so a list of lists raises a TypeError.

How it works and complexity

Membership checks in a set or dict are O(1) on average, so a single pass is enough. Checking item not in result against a list instead pushes the whole function to O(n^2), and interviewers will point it out.

Use a set for lookups, and always ask whether order matters.

Approach Time Space Keeps order
dict.fromkeys O(n) O(n) Yes
set() O(n) O(n) No
List membership loop O(n^2) O(n) Yes

Follow-up variations

Expect these in python interview coding questions for freshers rounds and beyond:

  • Remove duplicates from a sorted list in place using two pointers
  • Remove duplicates from a list of dictionaries by a chosen key
  • Return only the elements that appear more than once

6. Check if two strings are anagrams

The question and why interviewers ask it

Comparison of the sorting and Counter approaches for checking anagrams, with time, space, and verdicts.

Given two strings, return True if they use the same characters in the same counts, such as "listen" and "silent". It is a favorite in python coding questions for interview screens because it tests whether you reach for sorting or counting instead of comparing characters one by one. Ask whether case and spaces matter before you start.

Solution with code

Start with the sorting version, then show the counter version that most interviewers want.

from collections import Counter

def is_anagram_sorted(a, b):
    return sorted(a.lower()) == sorted(b.lower())

def is_anagram(a, b):
    a, b = a.lower(), b.lower()
    return len(a) == len(b) and Counter(a) == Counter(b)

print(is_anagram("Listen", "Silent"))  # True
print(is_anagram("python", "typhons"))  # False

Checking length first is a cheap early exit. Mention that you would strip spaces and punctuation if the problem asks for phrase anagrams.

How it works and complexity

Sorting puts both strings in a canonical order, so equal results mean equal letters. Counter builds a frequency map for each string, and comparing two dictionaries is a single pass over the keys.

Anagrams share the same character counts, so count them instead of comparing positions.

Approach Time Space
Sorting O(n log n) O(n)
Counter O(n) O(k), k = distinct characters

Follow-up variations

Expect one of these next, often phrased as part of python interview coding questions and answers sets:

  • Group a list of words into anagram groups using sorted words as dictionary keys
  • Find every anagram of a pattern inside a longer string with a sliding window
  • Check whether one string can be rearranged to form a palindrome

7. Count character frequency in a string

The question and why interviewers ask it

Given a string, return how many times each character appears, so "banana" gives b:1, a:3, n:2. It is a staple of python interview questions coding rounds because it tests dictionaries and whether you know the standard library. Interviewers also watch for case and space handling, so ask whether "A" and "a" count as the same character.

Solution with code

Write the manual dictionary version first, then show Counter.

from collections import Counter

def char_frequency(s):
    freq = {}
    for ch in s:
        freq[ch] = freq.get(ch, 0) + 1
    return freq

print(char_frequency("banana"))  # {'b': 1, 'a': 3, 'n': 2}
print(Counter("banana").most_common(1))  # [('a', 3)]

The get call with a default of 0 avoids a KeyError on the first sighting. Counter does the same work, and most_common handles the "top k" follow-up for free.

How it works and complexity

Each character triggers one dictionary lookup and one write, both O(1) on average. A single pass is enough, and the dictionary stores only distinct characters.

One pass and a hash map beat any nested loop.

Approach Time Space
Manual dict O(n) O(k)
Counter O(n) O(k)
s.count() per character O(n^2) O(k)

Avoid calling s.count(ch) inside the loop. It rescans the whole string each time, and interviewers will call it out.

Follow-up variations

These show up in many python code interview questions and answers sets, so try them next:

  • Find the first non-repeating character in a string
  • Return the most frequent character and break ties by first appearance
  • Print the frequencies sorted by count, highest first

8. Check if a number is prime

The question and why interviewers ask it

Write a function that returns True if a number is prime, meaning it has exactly two divisors, 1 and itself. It is a regular in code interview questions python candidates face because a naive answer is easy and a good answer needs one insight. Handle the edge cases first: 0, 1, and negatives are not prime, and 2 is the only even prime.

Solution with code

Start with the square root limit. You only need to test divisors up to the square root of n, and you can skip even numbers.

import math

def is_prime(n):
    if n < 2:
        return False
    if n % 2 == 0:
        return n == 2
    for i in range(3, math.isqrt(n) + 1, 2):
        if n % i == 0:
            return False
    return True

print([x for x in range(20) if is_prime(x)])  # [2, 3, 5, 7, 11, 13, 17, 19]

Use math.isqrt instead of n ** 0.5. It returns an exact integer and avoids float rounding errors on large inputs.

How it works and complexity

If n has a factor larger than its square root, it must also have a smaller partner. That means checking up to the root is enough to prove a number is prime.

Any composite number has a factor at or below its square root.

Approach Time Space
Test every number up to n O(n) O(1)
Trial division to the square root O(sqrt n) O(1)
Sieve of Eratosthenes (all primes up to n) O(n log log n) O(n)

Trial division is fine for a single number. When the task is to find many primes, a sieve is the better tool, and you should say so.

Follow-up variations

These appear in python interview coding questions for experienced candidates and in fresher rounds too:

  • Print all primes up to n using the Sieve of Eratosthenes
  • Return the prime factors of a number
  • Find the nth prime number
  • Test very large numbers with the Miller-Rabin algorithm

9. Flatten a nested list

The question and why interviewers ask it

Given a list that may hold other lists at any depth, return one flat list. For example, [1, [2, [3, 4]], 5] becomes [1, 2, 3, 4, 5]. It is one of the python code questions for interview rounds that tests recursion and how you handle uneven structure. Ask whether tuples should be flattened too. Strings are the trap, because a string is iterable and naive code recurses on it forever.

Solution with code

Start with the recursive version, then show a stack-based one.

def flatten(items):
    result = []
    for item in items:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result

def flatten_iterative(items):
    stack = items[::-1]
    result = []
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            stack.extend(reversed(item))
        else:
            result.append(item)
    return result

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

Check isinstance(item, list) instead of testing for any iterable, so strings stay whole. The stack version avoids the recursion limit on deeply nested input.

How it works and complexity

The recursive function visits every element once. Each nested list triggers a call that returns its own flat list, and extend merges it upward. The iterative version replaces the call stack with an explicit one.

Recurse on lists, append everything else, and keep strings whole.

Approach Time Space
Recursive with extend O(n * d), d = depth O(d) stack plus output
Iterative stack O(n) O(n)
Generator with yield from O(n) O(d)

The extra factor of d in the first row comes from copying results at each level. Mention it before the interviewer does.

Follow-up variations

Expect one of these after the basic answer:

  • Write a generator using yield from that flattens lazily
  • Flatten only one level with itertools.chain.from_iterable
  • Add a depth parameter that stops flattening after a set number of levels
  • Flatten a nested dictionary into keys like "a.b.c"

10. Implement binary search

The question and why interviewers ask it

A hand holds the middle block of a sorted row while half the blocks are set aside.

Given a sorted list and a target, return the target's index, or -1 if it is missing. Panels often save this for last among python coding questions interview sets, because it looks simple and off-by-one errors sink most first attempts. Test your function against these inputs:

  • An empty list
  • A single element
  • The target at the first or last position
  • A target that is not in the list

Solution with code

Start with the iterative version. It avoids recursion limits and is what most interviewers expect.

def binary_search(nums, target):
    low, high = 0, len(nums) - 1
    while low <= high:
        mid = (low + high) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

print(binary_search([1, 3, 5, 7, 9, 11], 7))  # 3

In real projects, the bisect module does this work for you. Still, write the loop by hand first.

How it works and complexity

Each pass compares the middle element with the target and discards half of the remaining range. A list of one million items needs about 20 comparisons. You do not need low + (high - low) // 2 here, because Python integers never overflow.

Halve the search range on every step, and only do it on sorted data.

Approach Time Space
Iterative O(log n) O(1)
Recursive O(log n) O(log n) stack
Linear scan O(n) O(1)

Follow-up variations

Expect the interviewer to change the problem, not stop at the basic answer. Practice these next:

  • Find the first and last position of a target in a list with duplicates
  • Search in a rotated sorted array
  • Return the index where a missing value should be inserted
  • Compute an integer square root with binary search

How to practice before your interview

Practice works best when you write code before you run it, then check the result. Pick one question a day, solve it in a plain editor, and say the time and space complexity out loud. Then rewrite it a second way, such as a loop and a recursive version. That habit matters more than memorizing answers.

Once you can solve all 10 problems cold, the python coding questions interview panels ask will feel familiar. Spend your last study sessions on the follow-up variations, because that is where interviewers separate prepared candidates from rehearsed ones.

If you hire developers, use this same list to run a consistent first screen. Then search 180,000+ verified developer profiles by skill, experience, and location on Olibr, and shortlist Python talent for free.

For engineers

Find work worth your time.

Live engineering roles across India and the US, matched to your stack. Build a profile recruiters actually discover.

Browse jobsHow it works

O
§ The author

Olibr Team

Reviewed by Raman Gupta, Founder, Olibr

Filed underHiring Tips
Reading time17 min · 3,315 words

PublishedOctober 7, 2026

CategoryHiring Tips
Enjoyed this piece?Share it with someone who would find it useful.
§ Stay in the loop

Don’t miss the next one.

We publish essays on engineering, hiring, and building teams. Subscribe and we’ll send them when they land.

Unsubscribe anytime · one letter, never more