Python Coding Interview Questions with Solutions (2027)

40 Python coding interview problems with solutions and complexity: strings, hash maps, sliding window, heaps, LRU cache, plus scenario rounds.

Sep 6, 2025 - 11:15
Nov 10, 2026 - 23:32
 0  104
TOPICInterview Q & APractical guide
Python Coding Interview Questions with Solutions (2027)

Python coding interview questions ask you to write working code live: reverse or count things in strings, find pairs in arrays, group data with dictionaries, walk trees, and write small scripts that parse files. Interviewers judge correctness first, then time and space complexity, edge cases, and how clearly you explain each step while you type. This page has 40 coding problems with tested-style solutions, grouped by level, followed by scenario rounds.

If you want concept questions (what is the GIL, list vs tuple, decorators explained), use our 150+ Python interview questions for DevOps. If your interview is for an automation or cloud role, the scenario-based Python interview questions for DevOps cover subprocess, boto3 and log parsing in depth. This page is for the coding round itself: a blank editor, a problem statement and 30 to 45 minutes.

Key takeaways

  • Most coding rounds reuse a small set of patterns: hash maps, two pointers, sliding windows, stacks, sorting with a key, BFS/DFS and simple dynamic programming.
  • Say the brute force first, give its complexity, then improve it. Interviewers reward the reasoning as much as the final code.
  • Use the standard library on purpose: collections.Counter, defaultdict, deque, heapq, bisect and itertools turn many problems into a few lines.
  • Freshers are tested on strings, lists and dictionaries. Candidates with 2 to 5 years get sliding windows, heaps, intervals and file processing. Senior rounds add design-flavoured code such as an LRU cache or a rate limiter.
  • Always test out loud with an empty input, a single element, duplicates and a large input before you say "done".

How a Python coding round is scored

Most interviewers use a short rubric even when they do not show it to you. Knowing it tells you where to spend your time.

What they checkWhat a strong answer showsCommon mistake
UnderstandingYou restate the problem and ask about input size, duplicates and empty inputTyping before asking a single question
CorrectnessCode runs on the examples and on edge cases you nameOff-by-one errors in loops and slices
ComplexityYou state Big-O time and space without being askedHidden O(n) work inside a loop, such as x in list
Python fluencyIdiomatic use of comprehensions, unpacking and the standard libraryWriting Java-style index loops everywhere
CommunicationYou explain trade-offs and test cases as you goSilent coding for 20 minutes

Python coding questions for freshers

1. Reverse a string without using slicing.

Build the result from the end, or use reversed() with join. Mention that s[::-1] is the idiomatic answer if slicing is allowed.

def reverse(s: str) -> str:
    return "".join(reversed(s))

Time O(n), space O(n). Strings are immutable, so repeated result = ch + result is O(n squared) and worth avoiding.

2. Check whether a string is a palindrome, ignoring case and non-letters.

Filter to alphanumeric characters, lowercase them, and compare with two pointers so you do not build a second copy.

def is_palindrome(s: str) -> bool:
    i, j = 0, len(s) - 1
    while i < j:
        if not s[i].isalnum():
            i += 1
        elif not s[j].isalnum():
            j -= 1
        elif s[i].lower() != s[j].lower():
            return False
        else:
            i, j = i + 1, j - 1
    return True

3. Count how often each word appears in a sentence.

Use collections.Counter after normalising case. Interviewers often follow up with "top three words", which is most_common(3).

from collections import Counter

def word_counts(text: str) -> Counter:
    return Counter(text.lower().split())

4. Find the first non-repeating character in a string.

Count characters in one pass, then scan again in order. Dictionaries keep insertion order, but the second scan over the string is clearer.

from collections import Counter

def first_unique(s: str):
    counts = Counter(s)
    for ch in s:
        if counts[ch] == 1:
            return ch
    return None

5. Check if two strings are anagrams.

Compare character counts. Sorting both strings also works but costs O(n log n) instead of O(n).

from collections import Counter

def is_anagram(a: str, b: str) -> bool:
    return Counter(a) == Counter(b)

6. Return the indices of two numbers that add up to a target (two sum).

Store each number's index in a dictionary and look up the complement. This turns an O(n squared) double loop into one pass.

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 None

7. Remove duplicates from a list while keeping the original order.

dict.fromkeys keeps the first occurrence of each item in insertion order. A set alone loses order.

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

8. Find the second largest distinct number in a list.

Track the top two values in one pass and handle lists with fewer than two distinct values.

def second_largest(nums):
    first = second = None
    for n in nums:
        if first is None or n > first:
            first, second = n, first
        elif n != first and (second is None or n > second):
            second = n
    return second

9. Write FizzBuzz for 1 to n.

Check 15 first, or build the string from parts. The point is clean conditions, not cleverness.

def fizzbuzz(n):
    for i in range(1, n + 1):
        out = ("Fizz" if i % 3 == 0 else "") + ("Buzz" if i % 5 == 0 else "")
        print(out or i)

10. Check whether a number is prime.

Test divisors up to the square root, skipping even numbers after 2. Use math.isqrt to avoid float rounding.

import math

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

11. Return the first n Fibonacci numbers.

Use iteration, not naive recursion, which is exponential. A generator is a good follow-up answer.

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

12. Flatten a nested list of arbitrary depth.

Recurse into lists and yield everything else. Mention that very deep nesting can hit the recursion limit, and an explicit stack avoids it.

def flatten(items):
    for x in items:
        if isinstance(x, list):
            yield from flatten(x)
        else:
            yield x

13. Merge two sorted lists into one sorted list.

Use two pointers and append the remainder. heapq.merge does the same lazily, which is worth naming.

def merge_sorted(a, b):
    i = j = 0
    out = []
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            out.append(a[i]); i += 1
        else:
            out.append(b[j]); j += 1
    return out + a[i:] + b[j:]

14. Check whether brackets in a string are balanced.

Push opening brackets on a stack and pop on each closing bracket. The string is balanced if every pop matches and the stack ends empty.

def balanced(s: str) -> bool:
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    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

15. Group a list of words by their anagram.

Use the sorted word as a key in a defaultdict(list).

from collections import defaultdict

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())

Python coding questions for 2 to 5 years of experience

16. Find the length of the longest substring without repeating characters.

Use a sliding window and remember the last index of each character. Move the left edge past the previous occurrence when you see a repeat.

def longest_unique(s: str) -> int:
    last, left, best = {}, 0, 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best

Time O(n), space O(k) where k is the alphabet size.

17. Return the k most frequent elements in a list.

Counter.most_common(k) is acceptable. If the interviewer wants the mechanism, use heapq.nlargest, which is O(n log k).

import heapq
from collections import Counter

def top_k(nums, k):
    counts = Counter(nums)
    return heapq.nlargest(k, counts, key=counts.get)

18. Merge overlapping intervals.

Sort by start, then extend the last interval when the next one overlaps.

def merge_intervals(intervals):
    out = []
    for start, end in sorted(intervals):
        if out and start <= out[-1][1]:
            out[-1][1] = max(out[-1][1], end)
        else:
            out.append([start, end])
    return out

19. Rotate a list to the right by k steps.

Normalise k with modulo first so large k and empty lists are safe. collections.deque.rotate is the library answer.

def rotate(nums, k):
    if not nums:
        return nums
    k %= len(nums)
    return nums[-k:] + nums[:-k]

20. Find the maximum sum of a contiguous subarray.

Kadane's algorithm: keep the best sum ending at the current position and the best seen overall.

def max_subarray(nums):
    best = cur = nums[0]
    for n in nums[1:]:
        cur = max(n, cur + n)
        best = max(best, cur)
    return best

21. Implement binary search and return the index or -1.

Keep the loop condition and the midpoint update consistent. Then mention bisect.bisect_left for production code.

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

22. Compute the product of all elements except self, without division.

Do one pass for prefix products and one backwards pass for suffix products.

def product_except_self(nums):
    out = [1] * len(nums)
    prefix = 1
    for i, n in enumerate(nums):
        out[i] = prefix
        prefix *= n
    suffix = 1
    for i in range(len(nums) - 1, -1, -1):
        out[i] *= suffix
        suffix *= nums[i]
    return out

23. Count the number of islands in a grid of "1" and "0".

Scan every cell and flood-fill each new island with BFS. A deque avoids recursion limits on large grids.

from collections import deque

def count_islands(grid):
    rows, cols = len(grid), len(grid[0]) if grid else 0
    seen, islands = set(), 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1" and (r, c) not in seen:
                islands += 1
                q = deque([(r, c)])
                seen.add((r, c))
                while q:
                    x, y = q.popleft()
                    for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
                        if 0 <= nx < rows and 0 <= ny < cols \
                           and grid[nx][ny] == "1" and (nx, ny) not in seen:
                            seen.add((nx, ny))
                            q.append((nx, ny))
    return islands

24. Write a decorator that measures how long a function takes.

Use time.perf_counter and functools.wraps so the wrapped function keeps its name and docstring.

import functools, time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
    return wrapper

25. Write a generator that reads a large file in fixed-size chunks.

Read in a loop until an empty bytes object comes back. Memory stays flat regardless of file size.

def read_chunks(path, size=1024 * 1024):
    with open(path, "rb") as f:
        while chunk := f.read(size):
            yield chunk

26. Find all duplicate files in a directory tree by content.

Group by file size first (cheap), then hash only files that share a size. Hash in chunks so large files do not load into memory.

import hashlib
from collections import defaultdict
from pathlib import Path

def file_hash(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while chunk := f.read(65536):
            h.update(chunk)
    return h.hexdigest()

def duplicates(root):
    by_size = defaultdict(list)
    for p in Path(root).rglob("*"):
        if p.is_file():
            by_size[p.stat().st_size].append(p)
    by_hash = defaultdict(list)
    for paths in by_size.values():
        if len(paths) > 1:
            for p in paths:
                by_hash[file_hash(p)].append(p)
    return [g for g in by_hash.values() if len(g) > 1]

27. Parse a CSV file and return the average of one column per group.

Use csv.DictReader and keep running sums and counts so you only read the file once.

import csv
from collections import defaultdict

def average_by(path, group_col, value_col):
    total, count = defaultdict(float), defaultdict(int)
    with open(path, newline="") as f:
        for row in csv.DictReader(f):
            total[row[group_col]] += float(row[value_col])
            count[row[group_col]] += 1
    return {k: total[k] / count[k] for k in total}

28. Validate an IPv4 address string without regular expressions.

Split on dots, require four parts, digits only, no leading zeros, and each part from 0 to 255. Also mention that ipaddress.ip_address in the standard library does this in production.

def is_ipv4(s: str) -> bool:
    parts = s.split(".")
    if len(parts) != 4:
        return False
    for p in parts:
        if not p.isdigit() or (len(p) > 1 and p[0] == "0") or int(p) > 255:
            return False
    return True

29. Return the n-th row of Pascal's triangle.

Each row is built from the previous one by adding neighbours. It tests list handling more than maths.

def pascal_row(n):
    row = [1]
    for _ in range(n):
        row = [1] + [a + b for a, b in zip(row, row[1:])] + [1]
    return row

30. Count the ways to climb n stairs taking 1 or 2 steps at a time.

This is the Fibonacci recurrence in disguise. Show the memoised version with functools.cache, then the O(1) space loop.

def climb(n):
    a, b = 1, 1
    for _ in range(n):
        a, b = b, a + b
    return a

Senior Python coding questions

31. Implement an LRU cache with get and put in O(1).

collections.OrderedDict gives O(1) moves to the end and pops from the front. Mention functools.lru_cache for caching function results.

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.data = OrderedDict()

    def get(self, key):
        if key not in self.data:
            return -1
        self.data.move_to_end(key)
        return self.data[key]

    def put(self, key, value):
        self.data[key] = value
        self.data.move_to_end(key)
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)

32. Write a token bucket rate limiter.

Refill tokens based on elapsed time, allow a request when a token is available. Use a monotonic clock so system clock changes do not break it, and add a lock if threads share it.

import threading, time

class TokenBucket:
    def __init__(self, rate: float, capacity: int):
        self.rate, self.capacity = rate, capacity
        self.tokens = capacity
        self.updated = time.monotonic()
        self.lock = threading.Lock()

    def allow(self) -> bool:
        with self.lock:
            now = time.monotonic()
            self.tokens = min(self.capacity,
                              self.tokens + (now - self.updated) * self.rate)
            self.updated = now
            if self.tokens >= 1:
                self.tokens -= 1
                return True
            return False

33. Return a valid build order for tasks with dependencies.

Use Kahn's topological sort. If not every task gets scheduled, there is a cycle, which you should report. The standard library also has graphlib.TopologicalSorter.

from collections import defaultdict, deque

def build_order(deps):  # deps: {task: [tasks it depends on]}
    indegree = defaultdict(int)
    children = defaultdict(list)
    tasks = set(deps)
    for task, needs in deps.items():
        for n in needs:
            tasks.add(n)
            children[n].append(task)
            indegree[task] += 1
    q = deque(t for t in tasks if indegree[t] == 0)
    order = []
    while q:
        t = q.popleft()
        order.append(t)
        for c in children[t]:
            indegree[c] -= 1
            if indegree[c] == 0:
                q.append(c)
    if len(order) != len(tasks):
        raise ValueError("dependency cycle")
    return order

34. Merge k sorted lists efficiently.

Push the head of each list onto a heap with its list index, pop the smallest, push the next item from that list. Time O(n log k).

import heapq

def merge_k(lists):
    heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
    heapq.heapify(heap)
    out = []
    while heap:
        val, i, j = heapq.heappop(heap)
        out.append(val)
        if j + 1 < len(lists[i]):
            heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
    return out

35. Write a retry helper that only retries specific exceptions.

Accept the exception types as a parameter, use exponential backoff with jitter, and re-raise the last error. Retrying every exception hides bugs such as TypeError.

import random, time

def retry(func, exceptions, attempts=5, base=0.5):
    for attempt in range(1, attempts + 1):
        try:
            return func()
        except exceptions:
            if attempt == attempts:
                raise
            time.sleep(base * 2 ** (attempt - 1) + random.uniform(0, base))

36. Fetch many URLs concurrently with a limit on parallel requests.

For I/O-bound work, concurrent.futures.ThreadPoolExecutor with max_workers is the simplest correct answer. Collect errors per URL instead of failing the whole batch.

from concurrent.futures import ThreadPoolExecutor, as_completed
import urllib.request

def status(url):
    with urllib.request.urlopen(url, timeout=5) as r:
        return r.status

def check_all(urls, workers=10):
    results = {}
    with ThreadPoolExecutor(max_workers=workers) as pool:
        futures = {pool.submit(status, u): u for u in urls}
        for f in as_completed(futures):
            url = futures[f]
            try:
                results[url] = f.result()
            except Exception as exc:
                results[url] = repr(exc)
    return results

37. Find the median of a stream of numbers.

Keep a max-heap for the lower half (store negatives) and a min-heap for the upper half, and rebalance so their sizes differ by at most one.

import heapq

class RunningMedian:
    def __init__(self):
        self.low, self.high = [], []   # low is a max-heap via negatives

    def add(self, n):
        heapq.heappush(self.low, -n)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def median(self):
        if len(self.low) > len(self.high):
            return -self.low[0]
        return (-self.low[0] + self.high[0]) / 2

Scenario-based Python coding rounds

38. Your solution passes the examples but times out on large input. What do you do?

Look for hidden quadratic work first. The usual culprits are x in some_list inside a loop (switch to a set), string concatenation in a loop (collect parts and join), repeated sorting, and recursion without memoisation. State the new complexity after each change. If you still need speed, measure with cProfile before guessing.

39. The interviewer changes the problem halfway: the input no longer fits in memory. How do you adapt?

Switch to streaming. Read line by line or in chunks with a generator, keep only aggregates (counts, running sums, a heap of size k), and avoid building full lists. For sorting data larger than memory, describe external sort: sort chunks to temporary files, then combine them with heapq.merge.

import heapq
from collections import Counter

def top_ips(log_path, k=10):
    counts = Counter()
    with open(log_path) as f:
        for line in f:
            ip = line.split(" ", 1)[0]
            counts[ip] += 1
    return heapq.nlargest(k, counts.items(), key=lambda kv: kv[1])

Point out that the Counter still grows with the number of distinct IPs. If that is too large, mention approximate structures or a database.

40. You are asked to write code with tests in the same session. How do you structure it?

Write a small pure function first, then a few pytest cases that cover the normal path, an empty input and one edge case. Parametrised tests keep it short. Keep input and output (files, network) at the edges so the core logic is easy to test.

import pytest
from solution import is_ipv4

@pytest.mark.parametrize("value, expected", [
    ("192.168.1.1", True),
    ("256.1.1.1", False),
    ("01.2.3.4", False),
    ("1.2.3", False),
    ("", False),
])
def test_is_ipv4(value, expected):
    assert is_ipv4(value) is expected

Patterns to recognise quickly

If the problem says...Try this patternQuestions above
"pair", "complement", "seen before"Hash map lookup6, 7, 15
"longest substring", "window of size k"Sliding window16
"sorted array", "find position"Binary search or two pointers13, 21
"top k", "smallest", "stream"Heap17, 34, 37
"brackets", "undo", "most recent"Stack14
"grid", "connected", "shortest steps"BFS or DFS23
"dependencies", "order"Topological sort33
"number of ways", "best total"Dynamic programming20, 30

How to practise for the coding round

  1. Solve each problem above without looking, with a 25 minute timer, speaking your reasoning aloud.
  2. For every solution, write the Big-O time and space in a comment.
  3. Re-solve the same problem a week later in fewer lines using the standard library.
  4. Practise in a plain editor with no autocomplete, since many interview tools have none.
  5. If you target DevOps roles, add file, process and API tasks from our Python scripts for DevOps automation list.

For the wider interview, our advanced Python interview questions cover internals such as descriptors and metaclasses, and the 200 DevOps interview questions guide covers the Linux, Git and container rounds that often follow a Python screen. Python automation is also part of our DevOps training in Pune, offered in the Kharadi classroom and live online.

FAQ

How many problems should I practise before a Python coding interview?

Quality beats volume. Being able to solve the 40 problems here cleanly, explain their complexity and adapt them to a twist covers most patterns asked in screening rounds.

Can I use built-in functions like sorted() and Counter in a coding interview?

Usually yes, and using them well shows Python fluency. Ask first. If the interviewer wants the algorithm, write it by hand and mention the built-in you would use in production.

Which Python version should I use in a coding interview?

Use a currently supported Python 3 release. Avoid features from the newest release unless you know the interview platform supports them, and never write Python 2 syntax.

Do DevOps interviews include algorithm questions?

Some do, usually at an easy to medium level. DevOps rounds more often ask for practical scripts such as parsing logs, checking endpoints or processing CSV and JSON files.

What should I do if I get stuck during a coding question?

Say the brute-force approach and its complexity, write it if time is short, then look for the repeated work you can remove with a set, a dictionary or sorting. Interviewers often give hints when you think aloud.

How do I explain time complexity in Python answers?

Count the loops and the cost of each operation inside them. Remember that list membership and list.pop(0) are O(n), while set and dict lookups are O(1) on average.

References

Interested in learning more?Get a callback from our training advisors.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.