Autocoder

Python Coding Interview Questions with Solutions

Last updated 2026-11-19

Coding rounds in Python reward candidates who solve the problem and also write idiomatic code: dictionaries for lookups, comprehensions where they help, and built-in tools such as Counter, heapq and bisect. Each solution below states its time and space complexity, which is what interviewers ask for next.

The problems range from warm-ups used in screening calls to medium problems that appear in product-company rounds. Try to write each one yourself before reading the answer, and run the code to confirm the stated output.

LevelFresher to 3 years
FocusIdiomatic solutions with complexity
VersionPython 3.9 and later

How to present a solution

Clarify inputs and edge cases, state a brute-force idea and its cost, improve it, then code it and walk through one example. Mention complexity at the end in terms of n.

Practice next

For topic-by-topic practice see array interview questions and hashing interview questions. For round structure, read how to crack a DSA coding round and how to crack a Python interview.

Python Coding Interview Questions with Solutions: questions with worked answers

  1. 1

    FizzBuzz: print numbers 1 to n, replacing multiples of 3 with Fizz, of 5 with Buzz and of both with FizzBuzz.

    easy

    Check the combined case first, or build the string from parts. It runs in O(n) time with O(1) extra space. The build-from-parts version avoids a separate branch for 15.

    python
    def fizzbuzz(n):
        out = []
        for i in range(1, n + 1):
            s = ("Fizz" if i % 3 == 0 else "") + ("Buzz" if i % 5 == 0 else "")
            out.append(s or str(i))
        return out
    print(fizzbuzz(15)[-3:])    # ['13', '14', 'FizzBuzz']
  2. 2

    Two Sum: return indices of two numbers that add up to a target.

    easy

    Store each value's index in a dictionary as you scan. For each number, check whether target minus the number was already seen. This is one pass, O(n) time and O(n) space, against O(n squared) for checking all pairs.

    python
    def two_sum(nums, target):
        seen = {}
        for i, x in enumerate(nums):
            if target - x in seen:
                return [seen[target - x], i]
            seen[x] = i
        return []
    print(two_sum([2, 7, 11, 15], 9))    # [0, 1]
  3. 3

    Check whether a string is a valid palindrome ignoring case and punctuation.

    easy

    Filter to alphanumeric characters, lowercase them and compare with the reverse, or use two pointers moving inward to use O(1) extra space. Both are O(n) time.

    python
    def is_pal(s):
        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 += 1; j -= 1
        return True
    print(is_pal("No 'x' in Nixon"))    # True
  4. 4

    Group anagrams from a list of words.

    medium

    Use a canonical key for each word, such as the sorted characters, and group in a defaultdict. With words of length k, sorting costs O(k log k), so the total is O(n k log k) time and O(n k) space. A character-count tuple as the key makes it O(n k).

    python
    from collections import defaultdict
    def group(words):
        d = defaultdict(list)
        for w in words:
            d["".join(sorted(w))].append(w)
        return list(d.values())
    print(group(["eat", "tea", "tan", "ate", "nat", "bat"]))
    # [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
  5. 5

    Find the most frequent element and the top k frequent elements.

    medium

    Count with Counter, then take the top k with most_common, which uses a heap and costs O(n log k). For k equal to 1 a simple max over the counts is O(n). Bucket sort by frequency gives O(n) for the top-k problem.

    python
    from collections import Counter
    def top_k(nums, k):
        return [x for x, _ in Counter(nums).most_common(k)]
    print(top_k([1, 1, 1, 2, 2, 3], 2))    # [1, 2]
  6. 6

    Merge overlapping intervals.

    medium

    Sort by start, then sweep: if the next interval starts at or before the end of the last merged one, extend the end with max, otherwise append it. Sorting dominates, so O(n log n) time and O(n) space for the output.

    python
    def merge(iv):
        iv.sort(key=lambda x: x[0])
        out = [iv[0]] if iv else []
        for s, e in iv[1:]:
            if s <= out[-1][1]:
                out[-1][1] = max(out[-1][1], e)
            else:
                out.append([s, e])
        return out
    print(merge([[1, 3], [8, 10], [2, 6], [15, 18]]))   # [[1, 6], [8, 10], [15, 18]]
  7. 7

    Longest substring without repeating characters.

    medium

    Use a sliding window with a dictionary of last positions. When a character repeats inside the window, move the left edge just past its previous index. Each character is processed once: O(n) time, O(k) space for the alphabet size k.

    python
    def longest(s):
        last, left, best = {}, 0, 0
        for i, ch in enumerate(s):
            if ch in last and last[ch] >= left:
                left = last[ch] + 1
            last[ch] = i
            best = max(best, i - left + 1)
        return best
    print(longest("abcabcbb"), longest("pwwkew"))   # 3 3
  8. 8

    Check for balanced brackets.

    medium

    Push opening brackets on a stack. For a closing bracket, the stack must be non-empty and its top must be the matching opener. At the end the stack must be empty. O(n) time and O(n) space.

    python
    def balanced(s):
        pair, st = {")": "(", "]": "[", "}": "{"}, []
        for ch in s:
            if ch in pair:
                if not st or st.pop() != pair[ch]:
                    return False
            elif ch in "([{":
                st.append(ch)
        return not st
    print(balanced("{[()]}"), balanced("(]"))   # True False
  9. 9

    Find the missing number in 0..n using O(1) extra space.

    medium

    The expected sum of 0..n is n(n+1)/2, so subtract the actual sum. An XOR of all indices and values also works and avoids large-sum overflow concerns in other languages. O(n) time, O(1) space.

    python
    def missing(nums):
        n = len(nums)
        return n * (n + 1) // 2 - sum(nums)
    print(missing([3, 0, 1]))    # 2
  10. 10

    Implement binary search and use bisect.

    medium

    Keep lo and hi bounds, compare the middle element and discard half each step: O(log n) time, O(1) space. The list must be sorted. The bisect module provides bisect_left and bisect_right for insertion points, which also solve lower-bound and upper-bound questions.

    python
    from bisect import bisect_left
    def search(a, x):
        lo, hi = 0, len(a) - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if a[mid] == x: return mid
            if a[mid] < x: lo = mid + 1
            else: hi = mid - 1
        return -1
    print(search([1, 3, 5, 7], 5), bisect_left([1, 3, 5, 7], 4))   # 2 2
  11. 11

    Design an LRU cache with O(1) get and put.

    hard

    Combine a hash map with a structure that tracks recency. In Python, OrderedDict does both: move_to_end marks a key as recent and popitem(last=False) evicts the oldest. Each operation is O(1), and space is O(capacity).

    python
    from collections import OrderedDict
    class LRU:
        def __init__(self, cap):
            self.cap, self.d = cap, OrderedDict()
        def get(self, k):
            if k not in self.d: return -1
            self.d.move_to_end(k)
            return self.d[k]
        def put(self, k, v):
            self.d[k] = v
            self.d.move_to_end(k)
            if len(self.d) > self.cap:
                self.d.popitem(last=False)
    c = LRU(2); c.put(1, 1); c.put(2, 2); c.get(1); c.put(3, 3)
    print(c.get(2), c.get(1))    # -1 1
  12. 12

    Reverse a linked list.

    medium

    Walk the list while keeping prev and current pointers, pointing each node's next to the previous node. O(n) time and O(1) space. The recursive version uses O(n) stack space.

    python
    class Node:
        def __init__(self, v, nxt=None): self.v, self.next = v, nxt
    def reverse(head):
        prev = None
        while head:
            head.next, prev, head = prev, head, head.next
        return prev
    h = reverse(Node(1, Node(2, Node(3))))
    print(h.v, h.next.v, h.next.next.v)    # 3 2 1
  13. 13

    Find the k-th largest element in a list.

    medium

    Maintain a min-heap of size k: push each element and pop when the size exceeds k. The root is the answer. O(n log k) time, O(k) space. heapq.nlargest(k, a)[-1] is the one-liner. Quickselect gives O(n) average.

    python
    import heapq
    def kth_largest(a, k):
        h = []
        for x in a:
            heapq.heappush(h, x)
            if len(h) > k: heapq.heappop(h)
        return h[0]
    print(kth_largest([3, 2, 1, 5, 6, 4], 2))   # 5
  14. 14

    Maximum subarray sum (Kadane's algorithm).

    hard

    At each element, the best sum ending here is either the element alone or the element added to the best sum ending at the previous position. Track the global maximum. O(n) time, O(1) space, and it handles all-negative arrays correctly when initialised with the first element.

    python
    def max_sub(a):
        cur = best = a[0]
        for x in a[1:]:
            cur = max(x, cur + x)
            best = max(best, cur)
        return best
    print(max_sub([-2, 1, -3, 4, -1, 2, 1, -5, 4]))   # 6

Frequently asked questions

Which Python features help most in coding rounds?

Dictionaries and sets for lookups, Counter and defaultdict for counting and grouping, heapq for priority queues, bisect for sorted lists, deque for queues and enumerate, zip and sorted with key for clean loops.

Is Python too slow for coding tests?

Usually not. Most platforms give extra time for Python, and a better algorithm matters far more than the language. Avoid O(n squared) inside loops and use built-ins.

How should I state complexity in an answer?

Give time and space separately, in terms of the input size, and name the dominant step, for example sorting being O(n log n).

Should I use recursion in Python?

Carefully. The default recursion limit is about 1000 frames, so deep recursion needs sys.setrecursionlimit or an iterative rewrite.

Related guides

More in Programming Language Interview Questions by Language

See all in this section