Python is often the preferred language for coding interviews due to its concise syntax and powerful built-in data structures. This guide covers the essential patterns you need to know to solve LeetCode-style problems efficiently.
1. Variables and Dynamic Typing
Python variables are dynamically typed, meaning a single variable can hold different types during execution.
# Variables are dynamically typed
n = 0
n = "abc"
# Multiple assignments
n, m = 0, "abc"
n, m, z = 0.125, "abc", False
# Increment (Note: n++ does not exist in Python)
n = n + 1
n += 1
# None is null (absence of value)
n = None
2. If-Statements and Loops
Python relies on indentation rather than curly braces or parentheses.
# If-statements
n = 1
if n > 2:
n -= 1
elif n == 2:
n *= 2
else:
n += 2
# while loops
n = 0
while n < 5:
print(n)
n += 1
# for loops (range)
for i in range(5): # 0 to 4
print(i)
for i in range(2, 6): # 2 to 5
print(i)
for i in range(5, 1, -1): # 5 down to 2
print(i)
3. Math Operations
import math
# Division
print(5 / 2) # 2.5 (Decimal by default)
print(5 // 2) # 2 (Integer division rounds down)
print(int(-3 / 2)) # Workaround to round towards zero
# Modulo
print(10 % 3) # 1
print(math.fmod(-10, 3)) # Consistent with other languages for negatives
# Helpers
math.floor(3/2)
math.ceil(3/2)
math.sqrt(2)
math.pow(2, 3)
# Infinity
float("inf")
float("-inf")
4. Arrays (Lists)
Lists in Python act as dynamic arrays and can be used as stacks.
arr = [1, 2, 3]
# Stack operations
arr.append(4) # Push
arr.pop() # Pop
# Access and Slicing
print(arr[-1]) # Last element
print(arr[1:3]) # Sublist (non-inclusive of last index)
# Initialization
n = 5
arr = [1] * n # [1, 1, 1, 1, 1]
# Sorting
arr.sort() # Ascending
arr.sort(reverse=True) # Descending
arr.sort(key=lambda x: len(x)) # Custom sort by length
# List Comprehension (Very useful for interviews)
arr = [i for i in range(5)]
arr_2d = [[0] * 4 for i in range(4)] # Correct way to init 2D array
5. Strings
Strings are similar to arrays but are immutable.
s = "abc"
# s[0] = "A" # Error
s += "def" # Creates a new string
# Conversion
int("123")
str(123)
ord("a") # ASCII value
# Join (Efficient way to combine strings)
strings = ["ab", "cd", "ef"]
print(" ".join(strings)) # "ab cd ef"
6. Queues and Deques
For $O(1)$ removals from the front, use collections.deque.
from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
queue.popleft() # O(1) time
queue.appendleft(3)
7. HashSets and HashMaps
The bread and butter of $O(1)$ lookup problems.
# HashSet
mySet = set()
mySet.add(1)
print(1 in mySet) # True
mySet.remove(1)
# HashMap (Dictionary)
myMap = {"alice": 90, "bob": 70}
myMap["charles"] = 80
print("alice" in myMap) # True
# Looping through Maps
for key, val in myMap.items():
print(key, val)
8. Tuples
Tuples are immutable and are often used as keys for HashMaps/HashSets because lists are not hashable.
tup = (1, 2, 3)
myMap = {(1, 2): 3} # Valid
# myMap[[1, 2]] = 3 # Invalid
9. Heaps (Priority Queues)
Python’s heapq implements a Min-Heap by default.
import heapq
minHeap = []
heapq.heappush(minHeap, 3)
heapq.heappop(minHeap)
# Max-Heap Workaround: Multiply values by -1
maxHeap = []
heapq.heappush(maxHeap, -1 * 3)
print(-1 * maxHeap[0])
# Heapify an existing array in O(n)
arr = [2, 1, 8, 4, 5]
heapq.heapify(arr)
10. Classes and Functions
class MyClass:
def __init__(self, nums):
self.nums = nums
self.size = len(nums)
def getLength(self):
return self.size
# Nested functions and nonlocal
def outer():
val = 1
def inner():
nonlocal val
val += 1
inner()
return val
🔗 View on GitHub: Python for Coding Interviews — Source