Basic Python Tips
Fast I/O operations are crucial for competitive programming.
from sys import stdin, stdout
input = stdin.readline
print = stdout.write
a, b = map(int, input().split())
arr = list(map(int, input().split()))
n = int(input())
matrix = [list(map(int, input().split())) for _ in range(n)]
print(f"{answer}\n")
Python One-Liners
Common Python one-liners that are frequently used in coding interviews.
squares = [x*x for x in range(10)]
matrix = [[0]*m for _ in range(n)]
evens = [x for x in range(10) if x % 2 == 0]
from itertools import combinations
combs = list(combinations([1,2,3], 2))
from itertools import permutations
perms = list(permutations([1,2,3]))
flattened = [item for sublist in matrix for item in sublist]
from collections import Counter
counts = Counter([1,1,2,3,3,3])
Data Structures
Lists (Arrays)
Lists are the most commonly used data structure in Python.
arr = []
arr.append(x)
arr.pop()
arr.insert(i, x)
arr.remove(x)
del arr[i]
arr.sort()
arr.sort(reverse=True)
arr.sort(key=lambda x: x[1])
sorted_arr = sorted(arr)
arr.reverse()
reversed_arr = arr[::-1]
arr[2:5]
arr[::-1]
arr[::2]
Using Lists as Queues
For efficient queue operations, use collections.deque.
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
queue.appendleft(0)
queue.pop()
queue.popleft()
Dictionaries (Hash Maps)
Dictionaries provide O(1) average case operations.
d = {}
d = dict()
d = {key: value for key, value in zip(keys, values)}
from collections import defaultdict
d = defaultdict(int)
d = defaultdict(list)
d = defaultdict(set)
from collections import Counter
c = Counter([1,1,2,3,3,3])
c.most_common(2)
c.update([1,2,3])
d[key] = value
value = d.get(key, default)
d.setdefault(key, default)
d.pop(key, default)
d.update(other_dict)
for key in d:
for key, value in d.items():
for value in d.values():
Sets
Sets are useful for maintaining unique elements and set operations.
s = set()
s = {1, 2, 3}
s = set([1, 2, 3])
s.add(x)
s.remove(x)
s.discard(x)
s.pop()
a | b
a & b
a - b
a ^ b
a <= b
a < b
Heaps (Priority Queues)
Python’s heapq implements a min-heap.
import heapq
heap = []
heapq.heappush(heap, 1)
min_val = heapq.heappop(heap)
min_val = heap[0]
heap = []
heapq.heappush(heap, -1)
max_val = -heapq.heappop(heap)
arr = [3, 1, 4, 1, 5]
heapq.heapify(arr)
k_largest = heapq.nlargest(k, arr)
k_smallest = heapq.nsmallest(k, arr)
Algorithms
Binary Search
Binary search is a fundamental algorithm for searching in sorted arrays.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
def binary_search_answer(low, high, condition):
while low < high:
mid = (low + high) // 2
if condition(mid):
high = mid
else:
low = mid + 1
return low
Graph Algorithms
Essential graph traversal and shortest path algorithms.
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for next_node in graph[start]:
if next_node not in visited:
dfs(graph, next_node, visited)
from collections import deque
def bfs(graph, start):
visited = {start}
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
curr_dist, curr = heapq.heappop(pq)
if curr_dist > distances[curr]:
continue
for neighbor, weight in graph[curr].items():
distance = curr_dist + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
Dynamic Programming
Dynamic programming solutions using memoization and tabulation.
def fibonacci(n, memo=None):
if memo is None:
memo = {}
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fibonacci(n-1, memo) + fibonacci(n-2, memo)
return memo[n]
def fibonacci(n):
if n <= 1:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
Common Patterns
Two Pointers Technique
The two-pointer technique is commonly used for array and string problems.
def two_sum(arr, target):
left, right = 0, len(arr) - 1
while left < right:
curr_sum = arr[left] + arr[right]
if curr_sum == target:
return [left, right]
elif curr_sum < target:
left += 1
else:
right -= 1
return []
def find_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
Sliding Window Pattern
Sliding window patterns for substring and subarray problems.
def max_sum_subarray(arr, k):
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(len(arr) - k):
window_sum = window_sum - arr[i] + arr[i + k]
max_sum = max(max_sum, window_sum)
return max_sum
def longest_substring_k_distinct(s, k):
char_count = {}
max_length = start = 0
for end, char in enumerate(s):
char_count[char] = char_count.get(char, 0) + 1
while len(char_count) > k:
left_char = s[start]
char_count[left_char] -= 1
if char_count[left_char] == 0:
del char_count[left_char]
start += 1
max_length = max(max_length, end - start + 1)
return max_length
Time Complexity Reference
Understanding time complexity is crucial for optimizing solutions.
Common Operations
dict.get(key)
set.add(item)
list[index]
binary_search(sorted_list)
heap operations
for loop
list.index(item)
max(list)
min(list)
sorted(list)
list.sort()
nested for loops
recursive fibonacci
generating all subsets
generating all permutations
Built-in Functions and Libraries
Essential Python Functions
abs(-5)
pow(2, 3)
round(3.14159, 2)
float('inf')
float('-inf')
s.strip()
s.lower()
s.upper()
s.split(',')
''.join(list)
Common Libraries
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
from functools import lru_cache
Best Practices for Interviews
Code Organization
- Write clean, readable code
- Use meaningful variable names
- Add comments for complex logic
- Break down complex problems into smaller functions
Problem-Solving Approach
- Understand the problem completely
- Work through examples
- Consider edge cases
- Start with brute force solution
- Optimize the solution
- Test your code
Common Pitfalls to Avoid
- Off-by-one errors in array indexing
- Not handling edge cases
- Forgetting to handle null/None inputs
- Not considering integer overflow
- Modifying collections while iterating