Python-Specific Strategies
Python Idioms for Interviews
# ✅ Use Python built-ins
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
# ✅ Use list comprehensions
def filter_even(nums):
return [x for x in nums if x % 2 == 0]
# ✅ Use enumerate instead of range(len())
for i, val in enumerate(nums):
print(f'{i}: {val}')
# ✅ Use zip for parallel iteration
for name, age in zip(names, ages):
print(f'{name} is {age}')
# ✅ Use collections for common patterns
from collections import Counter, defaultdict, deque
# Counter for frequency
freq = Counter(words)
# defaultdict for grouping
groups = defaultdict(list)
for item in items:
groups[item['key']].append(item)
# deque for O(1) pops from both ends
queue = deque()
queue.append(1) # Add to right
queue.popleft() # Remove from left
Common Python Interview Questions
# 1. What is the difference between list and tuple?
# List: mutable, []. Tuple: immutable, ()
# 2. What is a dictionary?
# Hash map with O(1) average lookup
# 3. What is list comprehension?
# Concise way to create lists: [x for x in range(10)]
# 4. What is the difference between '==' and 'is'?
# == compares values, is compares identity
# 5. What are *args and **kwargs?
# *args: variable positional arguments
# **kwargs: variable keyword arguments
# 6. What is a decorator?
# Function that modifies another function
# 7. What is a generator?
# Function using yield for lazy evaluation
# 8. What is the GIL?
# Global Interpreter Lock - allows only one thread
Time Complexity Awareness
# Know common complexities
# O(1): dict lookup, list append
# O(n): list search, string concatenation
# O(n^2): nested loops
# O(n log n): sorting
# Example: Two Sum
# Brute force O(n^2)
def two_sum_brute(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
# Optimal O(n)
def two_sum_optimal(nums, target):
seen = {}
for i, num in enumerate(nums):
if target - num in seen:
return [seen[target - num], i]
seen[num] = i
Space Complexity
# Know when you trade space for time
# Example: Two Sum uses O(n) space for O(n) time
# In-place solutions
# Example: Remove duplicates from sorted array
def remove_duplicates(nums):
if not nums:
return 0
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[read - 1]:
nums[write] = nums[read]
write += 1
return write
Interview Communication
Ask Clarifying Questions
# Before coding, ask:
# 1. What are the input constraints?
# 2. Can there be edge cases (empty, null, negative)?
# 3. What should I return if no solution exists?
# 4. Is the input sorted?
# 5. Can there be duplicates?
# Example:
def two_sum(nums, target):
# Questions to ask:
# - Can nums be empty? (assume no)
# - Can there be negative numbers? (yes)
# - Can there be duplicates? (yes)
# - Is there always exactly one solution? (yes)
pass
Walk Through Your Approach
# Before coding:
# 1. Explain your approach
# 2. Discuss time/space complexity
# 3. Mention edge cases
# 4. Ask if they want you to proceed
# Example explanation:
# "I'll use a hash map to store seen numbers.
# For each number, I check if target - num exists.
# Time: O(n), Space: O(n)
# Edge cases: empty array, no solution"
Test Your Code
# After coding, test with:
# 1. Normal case
# 2. Edge cases (empty, single element)
# 3. Large input
# 4. Special cases (all same, negative numbers)
# Example:
def test_two_sum():
# Normal case
assert two_sum([2, 7, 11, 15], 9) == [0, 1]
# Edge cases
assert two_sum([3, 3], 6) == [0, 1]
assert two_sum([1, 2, 3], 10) == [] # No solution
print('All tests passed!')
test_two_sum()
Handle Follow-up Questions
# Common follow-ups:
# 1. Can you do it with O(1) space?
# 2. Can you handle duplicates?
# 3. Can you find all solutions?
# 4. Can you optimize for specific constraints?
# Example follow-up: Find all pairs
def two_sum_all(nums, target):
seen = set()
result = set()
for num in nums:
complement = target - num
if complement in seen:
result.add((min(num, complement), max(num, complement)))
seen.add(num)
return [list(pair) for pair in result]
Python-Specific Tips
# 1. Use meaningful variable names
# Bad: x, y, z
# Good: nums, target, result
# 2. Write clean, readable code
# Bad: a=[i for i in range(10) if i%2==0]
# Good: even_numbers = [num for num in range(10) if num % 2 == 0]
# 3. Use Pythonic constructs
# Bad: for i in range(len(nums)):
# Good: for i, num in enumerate(nums):
# 4. Handle edge cases early
# if not nums: return []
# if len(nums) < 2: return []
# 5. Use built-in functions when possible
# sum(), max(), min(), len(), sorted()
# collections.Counter, defaultdict, deque
Time Management
| Time | Action |
|------|--------|
| 0-2 min | Understand the problem, ask questions |
| 2-5 min | Explain your approach |
| 5-20 min | Write the code |
| 20-25 min | Test with examples |
| 25-30 min | Handle follow-ups, optimize |