Interview Prep

Python Interview Cheat Sheet

Common patterns, built-in functions, and data structure operations you need for coding interviews. Plus a Java vs Python comparison.

Why Python for Interviews?

Less boilerplate means more time thinking about the algorithm. In a 45-minute interview, every keystroke matters.

Built-in data structures — lists, dicts, sets, deques, heaps — no imports or wrapper classes needed for most.

Readable syntax — your interviewer can follow your code instantly, which means better communication scores.

Essential Data Structures & Operations

List (Dynamic Array)

  • AppendO(1)
  • Pop from endO(1)
  • Pop from indexO(n)
  • Access by indexO(1)
  • Slicing [a:b]O(b-a)
  • in operatorO(n)
  • sort()O(n log n)

Dict (Hash Map)

  • Get / SetO(1) avg
  • DeleteO(1) avg
  • in operatorO(1) avg
  • Iterate keysO(n)
Pro tip

Use defaultdict(list) or defaultdict(int) to avoid KeyError checks. Use Counter() for frequency maps.

Set (Hash Set)

  • Add / RemoveO(1) avg
  • in operatorO(1) avg
  • Union / IntersectionO(n)

deque (Double-Ended Queue)

  • append / appendleftO(1)
  • pop / popleftO(1)
Use for

BFS queues, sliding window problems, and any scenario needing O(1) operations on both ends.

heapq (Min Heap)

  • heappushO(log n)
  • heappopO(log n)
  • heapifyO(n)
  • nlargest / nsmallestO(n log k)
Max heap trick

Python only has min-heap. For max-heap, negate values: heappush(h, -val)

Common Interview 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 (Graph/Tree)

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)

DFS (Recursive)

def dfs(graph, node, visited): visited.add(node) for nei in graph[node]: if nei not in visited: dfs(graph, nei, visited)

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): count = Counter(nums) return [x for x, _ in count.most_common(k)]

Java vs Python — Interview Comparison

Same operations, different verbosity. In a timed interview, Python wins on speed-to-write.

Operation Java Python
Hash map Map<K,V> m = new HashMap<>(); m = {}
Check key exists map.containsKey(k) k in m
Queue (BFS) Queue<T> q = new LinkedList<>(); q = deque()
Enqueue / Dequeue q.offer(x); q.poll(); q.append(x); q.popleft()
Sort array Arrays.sort(arr); arr.sort()
Sort by custom key Arrays.sort(arr, (a,b) -> a[1]-b[1]); arr.sort(key=lambda x: x[1])
Max of array Collections.max(list); max(arr)
String to char array s.toCharArray() list(s)
List comprehension list.stream().filter(...).collect(...) [x for x in arr if x > 0]
Infinity Integer.MAX_VALUE float('inf')
Swap values int t=a; a=b; b=t; a, b = b, a
Return multiple new int[]{a, b} // or custom class return a, b

Python One-Liners for Interviews

# Reverse a list arr[::-1] # Flatten 2D list [x for row in matrix for x in row] # Get all digits of a number digits = [int(d) for d in str(n)] # Default dict for adjacency list graph = defaultdict(list) # Enumerate with index for i, val in enumerate(arr): # Zip two lists into pairs pairs = list(zip(keys, values)) # Count occurrences freq = Counter(arr) # Check if all/any conditions all(x > 0 for x in arr) any(x < 0 for x in arr) # Initialize 2D grid grid = [[0] * cols for _ in range(rows)] # Get unique elements preserving order seen = set() unique = [x for x in arr if x not in seen and not seen.add(x)]

The Deeper Insight

Languages are just syntax on top of the same ideas.

Variables, loops, conditionals, functions, recursion, OOP — these concepts are identical in every language. Once you truly master one language, learning another takes days, not months.

The strategy:

  • 🐍 Python — coding interviews (speed wins)
  • Java — university classes (learn OOP deeply)
  • TypeScript — web dev & real-world projects

The real skill is thinking in algorithms, not in any one language's syntax. Master the concepts — the language is just the vehicle.

Import Cheat Sheet

from collections import deque, defaultdict, Counter, OrderedDict 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 from typing import List, Optional, Dict, Tuple
Interview tip

Most interviewers allow all standard library imports. Always ask "Can I use collections/heapq?" at the start — they almost always say yes.