← All posts
DSAInterviewsPython

Python for Coding Interviews: The Cheat Sheet I Actually Use

Less boilerplate means more time on the algorithm. The data structures, patterns, and one-liners worth knowing cold, plus how Java compares.

3 min read AI-generated

In a 45-minute interview, every keystroke counts. That's the whole case for Python. Less boilerplate means more time thinking about the algorithm, the built-in data structures cover almost everything without wrapper classes, and the syntax is easy for your interviewer to follow, which helps your communication score.

The data structures and what they cost

StructureOperationCost
listappend, pop from end, indexO(1)
pop/insert at index, inO(n)
slice [a:b]O(b−a)
sort()O(n log n)
dictget, set, delete, inO(1) avg
setadd, remove, inO(1) avg
dequeappend/appendleft, pop/popleftO(1)
heapqheappush, heappopO(log n)
heapifyO(n)

Two things to remember. Use defaultdict(list) or defaultdict(int) to skip KeyError checks, and Counter() for frequency maps. And Python only has a min-heap, so for a max-heap you push negated values: heappush(h, -val).

Reach for deque for BFS queues and anything that needs O(1) at both ends. Popping from the front of a list is O(n).

The patterns, in Python

Two pointers

def two_sum_sorted(nums, target):
    l, r = 0, len(nums) - 1
    while l < r:
        s = nums[l] + nums[r]
        if s == target:
            return [l, r]
        elif s < target:
            l += 1
        else:
            r -= 1

Sliding window

def max_sum_k(nums, k):
    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

BFS

from collections import deque

def bfs(graph, start):
    q = deque([start])
    visited = {start}
    while q:
        node = q.popleft()
        for nei in graph[node]:
            if nei not in visited:
                visited.add(nei)
                q.append(nei)

Binary search

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

Frequency count

from collections import Counter

def top_k_frequent(nums, k):
    return [x for x, _ in Counter(nums).most_common(k)]

Java vs. Python, side by side

Same operations, very different amounts of typing:

OperationJavaPython
Hash mapnew HashMap<>(){}
Key existsmap.containsKey(k)k in m
BFS queuenew LinkedList<>()deque()
Enqueue / dequeueq.offer(x); q.poll();q.append(x); q.popleft()
Sort by keyArrays.sort(a, (x,y) -> x[1]-y[1])a.sort(key=lambda x: x[1])
InfinityInteger.MAX_VALUEfloat('inf')
Swapint t=a; a=b; b=t;a, b = b, a
Return two valuesnew int[]{a, b}return a, b

One-liners worth memorizing

# reverse
arr[::-1]
# flatten 2D
[x for row in matrix for x in row]
# digits of a number
[int(d) for d in str(n)]
# adjacency list
graph = defaultdict(list)
# 2D grid (not [[0]*cols]*rows)
grid = [[0] * cols for _ in range(rows)]
# every element passes
all(x > 0 for x in arr)
# zip into pairs
pairs = list(zip(keys, values))

The import block

from collections import deque, defaultdict, Counter
from heapq import heappush, heappop, heapify, nlargest, nsmallest
from bisect import bisect_left, bisect_right, insort
from itertools import permutations, combinations, product
from functools import lru_cache   # memoization for DP
from math import inf, ceil, floor, gcd, log2

Most interviewers allow the standard library. Ask "can I use collections and heapq?" at the start. They almost always say yes.

The bigger point

Languages are syntax on top of the same ideas. Variables, loops, functions, recursion, OOP: identical everywhere. Once you really know one language, picking up another takes days, not months.

My split: Python for interviews because speed wins, Java for university classes to learn OOP properly, TypeScript for web projects. The real skill is thinking in algorithms. The language is just the vehicle.

Drafted by AI from my notes and guides, reviewed by me.