Coding Techniques
Python Coding Interview Questions · Study material
Count steps to feel the difference between O(n²) and O(n)
For 1,000 items, comparing every pair takes about half a million steps; a set needs a thousand. Counting operations is a quick way to see complexity without timing code.
# Count steps instead of timing: O(n²) vs O(n) for "does the list contain a duplicate?"
def has_dup_quadratic(nums):
steps = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
steps += 1
if nums[i] == nums[j]:
return True, steps
return False, steps
def has_dup_linear(nums):
seen, steps = set(), 0
for n in nums:
steps += 1
if n in seen:
return True, steps
seen.add(n)
return False, steps
data = list(range(1000))
print(has_dup_quadratic(data), has_dup_linear(data))
(False, 499500) (False, 1000)
Pattern recognition cheat table
| If the problem says… | Try |
|---|---|
| "find a pair / have we seen it?" | hash map or set |
| "sorted array", "pair", "palindrome" | two pointers |
| "longest / shortest contiguous subarray or substring" | sliding window |
| "brackets", "next greater", "undo" | stack |
| "top k", "k-th largest", "schedule by priority" | heap (heapq) |
| "shortest path", "minimum steps", "level by level" | BFS with deque |
| "sorted", "find position", "minimum value that works" | binary search / bisect |
| "number of ways", "minimum cost", "longest sequence" | dynamic programming |
| "all combinations / permutations" | backtracking |
Useful standard-library tools
from collections import Counter, defaultdict, deque, OrderedDict
import heapq, bisect
from functools import lru_cache
from itertools import combinations, permutations, accumulate
Counter("banana").most_common(1) # [('a', 3)]
deque([1, 2, 3]).popleft() # O(1) queue
heapq.nlargest(2, [5, 1, 9, 3]) # [9, 5]
bisect.bisect_left([1, 3, 5], 4) # 2 – insertion point
list(accumulate([1, 2, 3])) # [1, 3, 6] – prefix sums Interview checklist
- Clarify inputs and edge cases before coding.
- Say the brute force and its complexity first.
- Name the pattern and data structure you will use.
- Write small, well-named functions.
- Test empty input, one element, duplicates and negatives.
- State time and space complexity at the end.
- Know the cost of built-ins (pop(0), in on a list, slicing).