Skip to content

Python Coding Interview Questions: 10 Problems, 6 Patterns, Solutions and Complexity

Gulab Chand Tejwani

Gulab Chand Tejwani

PMP · PL-300 · Microsoft Certified Trainer

· 10 min read

PythonCoding InterviewPython Interview QuestionsAlgorithmsData Structures
Python Coding Interview Questions: 10 Problems, 6 Patterns, Solutions and Complexity

Python coding interview questions are short problems you solve live, usually on strings, lists and dictionaries, where the interviewer watches how you think as much as whether the code runs. Most of them are variations on a handful of patterns: hash maps for lookups, two pointers, sliding windows, stacks, heaps for top-k, and recursion. If you can recognise the pattern, write a clean solution and state its time and space complexity, you'll handle most coding rounds for developer and analyst roles.

I'm Gulab Chand Tejwani from TechNet Consultancy. I've seen strong candidates freeze in coding rounds because they tried to remember a specific solution. Patterns travel better than memorised answers. So the ten problems below are grouped by pattern, each with a working solution, its complexity and the thing I'd want to hear you say out loud.

How should you approach a Python coding problem in an interview?

  1. Restate it and ask about edge cases: empty input, duplicates, negative numbers, very large input.
  2. Say the brute force and its complexity, even if you won't code it.
  3. Find the pattern that improves it.
  4. Code it cleanly, with clear names.
  5. Test with an example out loud, including an edge case.
  6. State complexity and any trade-off.
Six steps for a Python coding round: restate, brute force, find the pattern, code, test aloud, state complexity
The steps interviewers want to see, in order.

Pattern 1: Hash maps and sets

Use a dictionary or set when you need to answer "have I seen this?" or "how many of these?" in constant time.

1. First non-repeating character

from collections import Counter

def first_unique_char(s: str) -> int:
    counts = Counter(s)
    for i, ch in enumerate(s):
        if counts[ch] == 1:
            return i
    return -1

print(first_unique_char("leetcode"))      # 0
print(first_unique_char("loveleetcode"))  # 2
print(first_unique_char("aabb"))          # -1

Complexity: O(n) time, O(k) space where k is the number of distinct characters. Say: "Two passes, one to count, one to find the first count of one."

2. Group anagrams

from collections import defaultdict

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

print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

Complexity: O(n · m log m) for n words of length up to m. Say: "The sorted word is a key that's identical for all anagrams."

Pattern 2: Two pointers

Use two indexes moving towards each other (or one chasing the other) on sorted data or sequences.

3. Valid palindrome, ignoring non-alphanumeric characters

def is_palindrome(s: str) -> bool:
    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

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

Complexity: O(n) time, O(1) extra space. Say: "This avoids building a cleaned copy, so it uses constant extra memory."

4. Pair with a target sum in a sorted list

def pair_sum_sorted(nums: list[int], target: int) -> tuple[int, int] | None:
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return left, right
        if total < target:
            left += 1
        else:
            right -= 1
    return None

print(pair_sum_sorted([1, 3, 4, 6, 8, 11], 10))  # (2, 3)

Complexity: O(n) time, O(1) space. If the list weren't sorted, a hash map gives O(n) time with O(n) space.

Pattern 3: Sliding window

Use a window that grows and shrinks over a sequence when the question asks about the "longest", "shortest" or "maximum" contiguous part.

5. Longest substring without repeating characters

def longest_unique_substring(s: str) -> int:
    last_seen = {}
    start = best = 0
    for i, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= start:
            start = last_seen[ch] + 1
        last_seen[ch] = i
        best = max(best, i - start + 1)
    return best

print(longest_unique_substring("abcabcbb"))  # 3
print(longest_unique_substring("bbbbb"))     # 1
print(longest_unique_substring("pwwkew"))    # 3

Complexity: O(n) time, O(k) space. Say: "When I see a repeat inside the window, I move the start just past its last position."

6. Maximum sum of k consecutive values

def max_window_sum(nums: list[int], k: int) -> int:
    if not 1 <= k <= len(nums):
        raise ValueError("k must be between 1 and len(nums)")
    window = sum(nums[:k])
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]
        best = max(best, window)
    return best

print(max_window_sum([2, 1, 5, 1, 3, 2], 3))  # 9

Complexity: O(n) time instead of O(n · k) for recomputing each window. Say: "I'd check that k is between 1 and the list length first, because a window bigger than the list doesn't exist."

If the problem says...TryTypical complexity
'seen before', 'count', 'duplicate'Hash map or setO(n)
Sorted input, 'pair', 'palindrome'Two pointersO(n), O(1) space
'longest/shortest contiguous', 'window of k'Sliding windowO(n)
'matching brackets', 'next greater'StackO(n)
'top k', 'k largest', 'merge sorted'Heap (heapq)O(n log k)
'all combinations', tree or nested dataRecursion / DFSDepends on branching
Pick the pattern from the wording of the problem

Pattern 4: Stack

Use a stack when the most recent item decides what happens next.

7. Valid brackets

def valid_brackets(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

print(valid_brackets("{[()]}"))  # True
print(valid_brackets("([)]"))    # False
print(valid_brackets("(("))      # False

Complexity: O(n) time, O(n) space. Say: "The return not stack catches unclosed brackets at the end."

Pattern 5: Heap for top-k

heapq keeps the smallest item at the front, which makes "top k" problems efficient.

8. Top k most frequent words

import heapq
from collections import Counter

def top_k_words(words: list[str], k: int) -> list[str]:
    counts = Counter(words)
    return [w for w, _ in heapq.nlargest(k, counts.items(), key=lambda item: item[1])]

words = ["pmp", "sql", "python", "sql", "pmp", "sql", "dax"]
print(top_k_words(words, 2))  # ['sql', 'pmp']

Complexity: O(n log k). Say: "Counter.most_common(k) does the same in one line. I'd use it in real code and mention the heap if asked how it works." If ties matter, clarify the tie-break rule before coding.

Pattern 6: Recursion

Use recursion for nested structures and "all possibilities" problems.

9. Flatten a nested list

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

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

Complexity: O(n · d) for n values nested up to depth d, because each value is passed up through every enclosing generator; for shallow lists that's close to O(n). Say: "Very deep nesting could hit Python's recursion limit and slow down, so for untrusted input I'd use an explicit stack."

10. All subsets of a list

def subsets(nums: list[int]) -> list[list[int]]:
    result = []

    def build(i: int, current: list[int]) -> None:
        if i == len(nums):
            result.append(current[:])
            return
        build(i + 1, current)              # skip nums[i]
        current.append(nums[i])
        build(i + 1, current)              # take nums[i]
        current.pop()

    build(0, [])
    return result

print(subsets([1, 2, 3]))
# [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]

Complexity: O(n · 2ⁿ), because there are 2ⁿ subsets and copying each takes up to n. Say: "The output itself is exponential, so no solution can beat that."

Common Python operation costs: dict and set lookup O(1) average, list append O(1), list search O(n), sort O(n log n), heap push O(log n)
Average costs of common Python operations, per the Python wiki's TimeComplexity page.

Practice questions

Question 1Coding · Complexity

You need to check, many times, whether user IDs exist in a collection of a million IDs. Which structure gives the fastest average lookups?

  1. AA list
  2. BA set
  3. CA sorted list with a for loop
  4. DA tuple
Show answer and explanation

Correct answer: B

Set and dict lookups are O(1) on average. Searching a list or tuple is O(n). A sorted list allows O(log n) with binary search (bisect), but not with a plain loop.

Question 2Coding · Patterns

'Find the length of the shortest contiguous subarray whose sum is at least S (all numbers positive).' Which pattern fits best?

  1. AStack
  2. BHeap
  3. CSliding window
  4. DRecursion
Show answer and explanation

Correct answer: C

"Shortest contiguous" with positive numbers is a classic sliding window: grow the window until the sum reaches S, then shrink from the left while it still qualifies.

Question 3Coding · Python details

Inside the subsets solution, why does the code append current[:] rather than current?

  1. Acurrent[:] sorts the list
  2. BIt's faster
  3. Ccurrent isn't defined at that point
  4. Dcurrent keeps changing, so the result needs a copy of its state at that moment
Show answer and explanation

Correct answer: D

Appending current would store a reference to the same list, which later calls keep modifying, so every entry would end up the same. current[:] stores a snapshot.

Question 4Coding · Complexity

What is the time complexity of checking `x in my_list` inside a loop that runs over my_list itself (n items)?

  1. AO(n²)
  2. BO(n)
  3. CO(n log n)
  4. DO(1)
Show answer and explanation

Correct answer: A

in on a list scans up to n items, and doing that n times gives O(n²). Converting the list to a set first makes each check O(1) on average, so the loop becomes O(n).

How do you practise for Python coding rounds?

Pick one pattern a day. Solve three problems for it without looking anything up, run them, then read a better solution and rewrite yours. On day seven, do a mixed set under a timer. Two or three weeks of this beats months of reading solutions, because the round tests whether you can produce code under pressure.

Python interview practice is built for exactly that: 200+ coding questions you write and run in a browser editor, with hints when you're stuck, test checks and worked answers, covering Python developer, algorithm and data analyst tracks, for a one-time ₹199. For the conceptual side, see Python interview questions for freshers and Python interview questions for experienced developers. If the role includes SQL, the SQL interview practice store has a free ShopX set to start.

FAQ

What coding questions are asked in Python interviews?

Mostly problems on strings, lists and dictionaries: first unique character, anagrams, palindromes, two-sum, longest substring without repeats, valid brackets, top-k frequent items and flattening nested lists.

How do I prepare for a Python coding interview?

Learn the six common patterns (hash map, two pointers, sliding window, stack, heap, recursion), solve a few problems per pattern, and practise explaining your approach and its complexity out loud while you code.

Can I use built-in libraries like collections in a coding interview?

Usually yes. Counter, defaultdict, deque and heapq are standard Python. If the interviewer wants you to implement something by hand, they'll say so.

Do I need to know big-O notation for Python interviews?

Yes. You should be able to state the time and space complexity of your solution and explain why an improved version is faster.

Are coding rounds different for data analyst roles?

Often. Analyst rounds lean towards pandas and SQL tasks on a dataset, though a simple string or list problem can still appear. Developer roles focus more on algorithmic patterns like the ones above.

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.