Introduction & Syntax
Python Coding Interview Questions · Study material
Coding rounds at product companies, service companies and start-ups ask variations of the same few dozen problems: two sum, valid parentheses, longest substring without repeats, merge intervals, top k frequent, reverse a linked list, shortest path in a grid. What interviewers really test is whether you recognise the pattern behind a problem, choose the right data structure, state the time and space complexity, and write clean, correct code. This capstone topic shows the patterns in idiomatic Python and gives you 50 questions – including 20 complete coding problems with solutions, all run on Python 3.
On this page
- Complexity of Python's lists, dicts, sets, deques and heaps
- Hash map and two-pointer patterns
- Sliding window
- Stacks and heaps
- BFS and binary search
- Dynamic programming, and how to approach any problem
Know your data structures
| Operation | list | dict / set | deque | heapq (list) |
|---|---|---|---|---|
| index / lookup by key | O(1) by index | O(1) average | O(n) in the middle | min at [0]: O(1) |
| x in container | O(n) | O(1) average | O(n) | O(n) |
| add at end / remove from end | O(1) | O(1) | O(1) | push / pop: O(log n) |
| add / remove at front | O(n) | – | O(1) | – |
| sort | O(n log n) | – | – | heapify: O(n) |
Rule of thumb: membership tests in a loop → set; counting or lookups → dict (or Counter); queue → deque; "k largest/smallest" or a priority queue → heapq; sorted data → binary search with bisect.
Pattern 1: hash map
Trade memory for speed: store what you have seen in a dict or set so each new element is checked in O(1). Two sum, first unique character, anagram groups and duplicate detection all follow this pattern and turn O(n²) into O(n).
def two_sum(nums, target):
"""Indices of the two numbers that add up to target – O(n) with a dict."""
seen = {} # value -> index
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = i
return []
def first_unique(s):
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
return next((i for i, ch in enumerate(s) if counts[ch] == 1), -1)
print(two_sum([2, 7, 11, 15], 9), two_sum([3, 3], 6))
print(first_unique("leetcode"), first_unique("aabb"))
[0, 1] [0, 1] 0 -1
Pattern 2: two pointers
Two indices moving towards each other (or in the same direction) solve palindrome checks, pair sums in a sorted array, removing duplicates in place and merging sorted lists – in O(n) time and O(1) extra space.
def is_palindrome(s):
s = [c.lower() for c in s if c.isalnum()]
left, right = 0, len(s) - 1
while left < right: # move inwards from both ends
if s[left] != s[right]:
return False
left, right = left + 1, right - 1
return True
def pair_with_sum(sorted_nums, target): # needs SORTED input
i, j = 0, len(sorted_nums) - 1
while i < j:
total = sorted_nums[i] + sorted_nums[j]
if total == target:
return sorted_nums[i], sorted_nums[j]
if total < target:
i += 1
else:
j -= 1
return None
print(is_palindrome("A man, a plan, a canal: Panama"), is_palindrome("race a car"))
print(pair_with_sum([1, 3, 4, 6, 8, 11], 10), pair_with_sum([1, 2, 3], 9))
True False (4, 6) None
Pattern 3: sliding window
For "best contiguous subarray or substring" problems, keep a window and update it incrementally as it slides – adding the new element and removing the old – instead of recomputing every window. Variable-size windows grow and shrink, often with a dict of last positions or counts.
def max_sum_window(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k] # slide: add the new item, drop the old one
best = max(best, window)
return best
def longest_unique_substring(s):
last_seen = {}
start = best = 0
for i, ch in enumerate(s):
if last_seen.get(ch, -1) >= start: # repeat inside the window: move the start past it
start = last_seen[ch] + 1
last_seen[ch] = i
best = max(best, i - start + 1)
return best
print(max_sum_window([2, 1, 5, 1, 3, 2], 3))
print(longest_unique_substring("abcabcbb"), longest_unique_substring("pwwkew"), longest_unique_substring(""))
9 3 3 0
Pattern 4: stacks and heaps
A list used as a stack (append / pop) matches brackets, evaluates expressions and finds the next greater element. heapq keeps a min-heap in a list: heappush and heappop are O(log n), nlargest / nsmallest give the top k, and pushing (priority, item) tuples builds a priority queue (negate numbers for a max-heap).
import heapq
def balanced(s):
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([balanced(s) for s in ["([]{})", "(]", "((", "a(b)c"]])
nums = [7, 2, 9, 4, 1, 8]
print(heapq.nlargest(3, nums), heapq.nsmallest(2, nums))
heap = []
for task, priority in [("email", 3), ("bug", 1), ("docs", 5)]:
heapq.heappush(heap, (priority, task)) # min-heap: smallest priority first
print([heapq.heappop(heap)[1] for _ in range(len(heap))])
[True, False, False, True] [9, 8, 7] [1, 2] ['bug', 'email', 'docs']
Pattern 5: BFS and binary search
Breadth-first search with a deque finds the shortest path in an unweighted grid or graph and traverses trees level by level. Binary search halves a sorted range each step – O(log n) – and bisect gives the position or insertion point directly.
from collections import deque
import bisect
def shortest_path(grid, start, goal):
rows, cols = len(grid), len(grid[0])
queue = deque([(start, 0)])
seen = {start}
while queue:
(r, c), dist = queue.popleft()
if (r, c) == goal:
return dist
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), dist + 1))
return -1
grid = ["..#.",
".##.",
"...."]
print(shortest_path(grid, (0, 0), (0, 3)))
scores = [35, 48, 52, 67, 71, 89] # sorted
print(bisect.bisect_left(scores, 67), bisect.bisect_left(scores, 60)) # position / insertion point
7 3 3
Pattern 6: dynamic programming
When a problem breaks into overlapping sub-problems (ways to climb stairs, minimum coins, longest increasing subsequence), compute each sub-result once – top-down with memoisation (@lru_cache) or bottom-up in a table or a few variables.
def climb_stairs(n):
a, b = 1, 1 # ways to reach step 0 and step 1
for _ in range(n - 1):
a, b = b, a + b # ways(n) = ways(n-1) + ways(n-2)
return b
def max_subarray(nums): # Kadane: best sum ending here vs overall best
best = current = nums[0]
for n in nums[1:]:
current = max(n, current + n)
best = max(best, current)
return best
print([climb_stairs(n) for n in range(1, 8)])
print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]), max_subarray([-3, -1, -2]))
[1, 2, 3, 5, 8, 13, 21] 6 -1
How to approach a coding question
- Understand: restate the problem, ask about input size, duplicates, negatives, empty input.
- Examples: work through a small example and the edge cases by hand.
- Brute force first: say it and its complexity, then look for a pattern that improves it.
- Plan: choose the data structure; explain the idea before coding.
- Code: clean names, small helper functions, no premature tricks.
- Test and analyse: run your examples and edge cases; state time and space complexity.
Key points to remember
- dict/set lookups are O(1); list membership is O(n).
- Use deque for queues, heapq for priority and top-k problems.
- Two pointers need sorted input (or a palindrome-style symmetry).
- Sliding windows update incrementally instead of recomputing.
- BFS finds shortest paths in unweighted graphs.
- Binary search and bisect need sorted data.
- Always state complexity and test edge cases: empty, one element, duplicates, negatives.
Frequently asked questions
Is Python a good language for coding interviews?
Yes – its concise syntax and rich built-ins (dict, set, deque, heapq, Counter, bisect, lru_cache) let you focus on the algorithm. Do mention complexity, because built-ins hide costs (e.g. list.pop(0) is O(n)).
Can I use library functions such as sorted() or Counter?
Usually yes, but be ready to explain how they work and their complexity, or to implement the core idea yourself if asked.
What should I practise first?
Arrays and strings with hash maps, two pointers and sliding windows; then stacks, queues, heaps; then trees, graphs (BFS/DFS) and dynamic programming.
Where can I learn more?
Revise Python Functions and Choosing the Right Collection in the Python tutorial, then solve the coding problems below.