Skip to the content

Lesson 284 of 296

Python for coding interviews

What you will learn

  • Idioms that make solutions short: enumerate, zip, sorted with key
  • Generators
  • Classic problems in Python
  • Complexity of common operations
  • Common Python trick questions
On this page

Useful idioms

Python
names = ["sam", "ana", "leo"]
for i, name in enumerate(names):         # index and value
    print(i, name)

scores = [90, 72, 85]
for name, score in zip(names, scores):   # walk two lists together
    print(name, score)

people = [("sam", 30), ("ana", 25), ("leo", 41)]
print(sorted(people, key=lambda p: p[1]))               # by age
print(sorted(people, key=lambda p: (-p[1], p[0])))      # age high to low, then name
print(min(people, key=lambda p: p[1]))                  # ('ana', 25)
print(any(s > 80 for s in scores), all(s > 60 for s in scores))  # True True
print(float("inf") > 10**100)                           # True: handy start value for min

Generators

A generator produces values one at a time, only when asked, using yield. It uses very little memory even for huge sequences.

Python
def countdown(n: int):
    while n > 0:
        yield n
        n -= 1

print(list(countdown(3)))                      # [3, 2, 1]
print(sum(x * x for x in range(1_000_000)))    # generator expression: no big list in memory

Classic problems

Two sum (Lesson 125 solved it in TypeScript): return the indices of two numbers that add up to the target.

Python
def two_sum(nums: list[int], target: int) -> list[int]:
    seen: dict[int, int] = {}            # value -> index
    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]

Valid parentheses with a stack:

Python
def is_valid(s: str) -> bool:
    pairs = {")": "(", "]": "[", "}": "{"}
    stack: list[str] = []
    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(is_valid("([]{})"), is_valid("(]"), is_valid("(("))  # True False False

Group anagrams with a defaultdict:

Python
from collections import defaultdict

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

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

Top k frequent with Counter:

Python
from collections import Counter

def top_k(nums: list[int], k: int) -> list[int]:
    return [n for n, _ in Counter(nums).most_common(k)]

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

Breadth-first search on a grid, shortest number of steps:

Python
from collections import deque

def shortest_path(grid: list[str]) -> int:
    rows, cols = len(grid), len(grid[0])
    queue = deque([(0, 0, 0)])           # row, col, steps
    seen = {(0, 0)}
    while queue:
        r, c, steps = queue.popleft()
        if (r, c) == (rows - 1, cols - 1):
            return steps
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "." and (nr, nc) not in seen:
                seen.add((nr, nc))
                queue.append((nr, nc, steps + 1))
    return -1

print(shortest_path(["..#", "#..", "..."]))  # 4

Complexity of common operations

OperationCost
x in listO(n)
x in set / key in dictO(1) average
list.append / list.pop()O(1)
list.pop(0) / list.insert(0, x)O(n), use deque
sorted(list)O(n log n)
String += in a loopCan be O(n²) overall; collect parts in a list and "".join

Trick questions

QuestionAnswer
is vs ==?== compares values; is checks if it is the same object. Use is only with None.
Are Python ints limited in size?No, they grow as needed.
What does [[0] * 3] * 3 do wrong?It makes three references to the same inner list. Use [[0] * 3 for _ in range(3)].
Pass by value or reference?Neither: names are passed to the same objects. Mutating a list inside a function changes it outside; reassigning the name does not.
What is the GIL?The Global Interpreter Lock in standard CPython lets only one thread run Python code at a time, so threads help with waiting (I/O) but not CPU work. Use processes for CPU work. Newer versions also offer an optional build without the GIL.
list vs tuple?List is mutable; tuple is immutable and can be a dict key.
Python
grid_bad = [[0] * 3] * 3
grid_bad[0][0] = 1
print(grid_bad)    # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
print(grid)        # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

How to say it in an interview

"In Python interviews I use enumerate and zip instead of index loops, sorted with a key function, dicts and sets for O(1) lookups, Counter and defaultdict for counting and grouping, deque for BFS and heapq for priority queues. I avoid list.pop(0) and string concatenation in loops, and I know the traps: 'is' versus '==', the shared inner list from [[0]*3]*3, mutable default arguments, and that the GIL limits threads for CPU-heavy work."

Key words

WordMeaning
enumerateGives index and value while looping
zipWalks several iterables together
key functionA function that tells sorted/min/max what to compare
GeneratorA function using yield that produces values lazily
GILCPython's lock that lets one thread run Python code at a time

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.