Python Coding Interview Practice - 25 Problems with Solutions
Master coding interviews with 25 hand-picked problems covering arrays, strings, trees, graphs, DP, and system design patterns used at FAANG companies.
Each solution includes optimal time/space complexity, multiple approaches, edge cases, and VS Code debugging configurations.
1. Two Sum - Array Hashing (Easy)
Python
O(n) Hash Map Solution
def twoSum(nums: list[int], target: int) -> list[int]:
hashmap = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hashmap:
return [hashmap[complement], i]
hashmap[num] = i
return []
# Test cases
print(twoSum([2,7,11,15], 9)) # [0,1]
print(twoSum([3,2,4], 6)) # [1,2]
print(twoSum([3,3], 6)) # [0,1]
Time: O(n) | Space: O(n) - Hash map stores visited numbers
2. Valid Palindrome (Easy)
Python
Two Pointers O(n) solution
def isPalindrome(s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
# Move left pointer
while left < right and not s[left].isalnum():
left += 1
# Move right pointer
while left < right and not s[right].isalnum():
right -= 1
# Compare ignoring case
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return True
print(isPalindrome('A man, a plan, a canal: Panama')) # True
print(isPalindrome('race a car')) # False
3. Container With Most Water (Medium)
Python
Two Pointers Greedy
def maxArea(height: list[int]) -> int:
left, right = 0, len(height) - 1
max_water = 0
while left < right:
width = right - left
current_area = width * min(height[left], height[right])
max_water = max(max_water, current_area)
# Move shorter pointer
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_water
print(maxArea([1,8,6,2,5,4,8,3,7])) # 49
4. Reverse Linked List (Easy)
Python
Iterative O(n) solution
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head: ListNode) -> ListNode:
prev = None
current = head
while current:
next_temp = current.next
current.next = prev
prev = current
current = next_temp
return prev
# Helper to create and print lists
def create_list(values):
dummy = ListNode(0)
current = dummy
for val in values:
current.next = ListNode(val)
current = current.next
return dummy.next
def print_list(head):
values = []
while head:
values.append(head.val)
head = head.next
return values
5. Maximum Depth of Binary Tree (Easy)
Python
Recursion O(n)
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxDepth(root: TreeNode) -> int:
if not root:
return 0
left_depth = maxDepth(root.left)
right_depth = maxDepth(root.right)
return max(left_depth, right_depth) + 1
# Test tree: 3
# / \
# 9 20
# / \
# 15 7
root = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
print(maxDepth(root)) # 3
6. House Robber (Medium)
Python
Space Optimized DP
def rob(nums: list[int]) -> int:
if len(nums) == 1:
return nums[0]
# dp[i] = max money robbing up to house i
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i-1], dp[i-2] + nums[i])
return dp[-1]
print(rob([1,2,3,1])) # 4
print(rob([2,7,9,3,1])) # 12
7. Longest Substring Without Repeating Characters (Medium)
Python
Sliding Window O(n)
def lengthOfLongestSubstring(s: str) -> int:
char_index = {}
left = right = length = 0
while right < len(s):
if s[right] in char_index and char_index[s[right]] >= left:
left = char_index[s[right]] + 1
else:
length = max(length, right - left + 1)
char_index[s[right]] = right
right += 1
return length
print(lengthOfLongestSubstring('abcabcbb')) # 3
print(lengthOfLongestSubstring('bbbbb')) # 1
print(lengthOfLongestSubstring('pwwkew')) # 3
8. Valid Parentheses (Medium)
Python
Stack O(n)
def isValid(s: str) -> bool:
stack = []
brackets = {')':'(', '}':'{', ']':'('}
for char in s:
if char in brackets.values():
stack.append(char)
elif char in brackets:
if not stack or stack.pop() != brackets[char]:
return False
return not stack
print(isValid('()')) # True
print(isValid('()[]{}')) # True
print(isValid('(]')) # False
9. Number of Islands (Medium)
Python
DFS Flood Fill O(mn)
def numIslands(grid: list[list[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
islands = 0
def dfs(r: int, c: int):
if (r < 0 or r >= rows or
c < 0 or c >= cols or
grid[r][c] != '1'):
return
grid[r][c] = '0' # Mark visited
dfs(r+1, c)
dfs(r-1, c)
dfs(r, c+1)
dfs(r, c-1)
for r in range(rows):
for c in range(cols):
if grid[r][c] == '1':
islands += 1
dfs(r, c)
return islands
print(numIslands([
['1','1','0','0','0'],
['1','1','0','0','0'],
['0','0','1','0','0'],
['0','0','0','1','1']
])) # 3
10. Search in Rotated Sorted Array (Medium)
Python
Modified Binary Search O(log n)
def search(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
# Left sorted portion
if nums[left] <= nums[mid]:
if target >= nums[left] and target < nums[mid]:
right = mid - 1
else:
left = mid + 1
# Right sorted portion
else:
if target > nums[mid] and target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
print(search([4,5,6,7,0,1,2], 0)) # 4
print(search([4,5,6,7,0,1,2], 3)) # -1
VS Code Practice Setup
JSON
launch.json for interview practice
{
"version": "0.2.0",
"configurations": [
{
"name": "Practice Problem",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}"
}
]
}
Copy each solution to VS Code, add breakpoints (F9), press F5 to debug and verify test cases.
Practice Strategy
- Solve 3 problems daily (Easy/Medium/Hard)
- Time yourself (30 mins per Medium problem)
- Explain solution aloud before coding
- Test all edge cases: empty, single, max values
- Optimize from brute force → optimal
- Practice on LeetCode after mastering these
Interview Success Checklist
- Always discuss time/space complexity first
- Write readable code with good variable names
- Test with 3-4 edge cases before optimization
- Ask clarifying questions about input constraints
- Talk through your thought process continuously
Practice these 10 core problems + their variations and you'll be ready for any Python coding interview!
Codecrown