Fast I/O operations are crucial for competitive programming.
Copy
# Fast Inputfrom sys import stdin, stdoutinput = stdin.readline # Faster inputprint = stdout.write # Faster output# Multiple inputs on one linea, b = map(int, input().split())# List input on one linearr = list(map(int, input().split()))# Multiple lines inputn = int(input())matrix = [list(map(int, input().split())) for _ in range(n)]# Output formattingprint(f"{answer}\n") # Don't forget \n when using stdout.write
Common Python one-liners that are frequently used in coding interviews.
Copy
# List comprehensionsquares = [x*x for x in range(10)]matrix = [[0]*m for _ in range(n)] # n×m matrix# Conditional comprehensionevens = [x for x in range(10) if x % 2 == 0]# Generate combinationsfrom itertools import combinationscombs = list(combinations([1,2,3], 2)) # [(1,2), (1,3), (2,3)]# Generate permutationsfrom itertools import permutationsperms = list(permutations([1,2,3]))# Flatten 2D listflattened = [item for sublist in matrix for item in sublist]# Count elementsfrom collections import Countercounts = Counter([1,1,2,3,3,3]) # Counter({3:3, 1:2, 2:1})
For efficient queue operations, use collections.deque.
Copy
from collections import dequequeue = deque([1, 2, 3])queue.append(4) # Add to rightqueue.appendleft(0) # Add to leftqueue.pop() # Remove from rightqueue.popleft() # Remove from left
Dictionaries provide O(1) average case operations.
Copy
# Creationd = {}d = dict()d = {key: value for key, value in zip(keys, values)}# Default dictionaryfrom collections import defaultdictd = defaultdict(int) # Default value 0d = defaultdict(list) # Default value []d = defaultdict(set) # Default value set()# Counterfrom collections import Counterc = Counter([1,1,2,3,3,3])c.most_common(2) # Two most common elementsc.update([1,2,3]) # Add more elements# Operationsd[key] = valuevalue = d.get(key, default) # Returns default if key not foundd.setdefault(key, default) # Set default if key not foundd.pop(key, default) # Remove and return, optional defaultd.update(other_dict) # Merge dictionaries# Iterationfor key in d: # Iterate keysfor key, value in d.items(): # Iterate key-value pairsfor value in d.values(): # Iterate values
Sets are useful for maintaining unique elements and set operations.
Copy
# Creations = set()s = {1, 2, 3}s = set([1, 2, 3])# Operationss.add(x) # Add elements.remove(x) # Remove element (raises KeyError if not found)s.discard(x) # Remove element (no error if not found)s.pop() # Remove and return arbitrary element# Set operationsa | b # Uniona & b # Intersectiona - b # Differencea ^ b # Symmetric differencea <= b # Subseta < b # Proper subset
Dynamic programming solutions using memoization and tabulation.
Copy
# Top-down (Memoization)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]# Bottom-up (Tabulation)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]
The two-pointer technique is commonly used for array and string problems.
Copy
# Two pointers from endsdef 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 []# Fast and slow pointersdef 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