100 Python Tricks for DSA (Cheat Sheet)
Pythonic Loops & Conditions
- Use for x in arr instead of for i in range(len(arr)) if index not needed
- Use enumerate(arr) for (index, value) pairs
- Use zip(a, b) to iterate over two lists together
- List comprehensions for clean loops: [x*x for x in arr]
- Use if x instead of if x == True
- Use all() and any() for conditions over iterables
- Chained comparisons: if 1 < x <= 10
- Ternary operator: a if cond else b
- while loops for unknown iterations
- for-else for checking if break was used
- Use reversed(arr) for large list reverse
- Use sorted(arr) to preserve original list
- Use set to remove duplicates: list(set(arr))
- Use is for identity, == for equality
- Avoid modifying list while iterating
Data Structures Shortcuts
- collections.Counter for frequency maps
- collections.deque for fast pops from both ends
- Use set for fast membership test
- defaultdict(int) for auto-zero values
- heapq for priority queues
- heapq.nlargest(k, arr) for top-k elements
- dict.items() for key-value loop
- bisect for binary search on sorted list
- arr.count(x) for frequency (small arrays)
- max(arr, key=func) and min(arr, key=func)
- math.gcd(a, b) for GCD
- collections.OrderedDict to maintain order
- Tuple as dict key for multidimensional problems
- Use in with set/dict for fast lookup
- dict.pop(key, None) to safely delete key
Math & Number Tricks
- divmod(a, b) returns (quotient, remainder)
- pow(x, y, mod) for modular exponentiation
- math.isqrt(n) for integer sqrt
- math.factorial(n) for factorial
- math.log2(x) for base-2 log
- round(num, digits) to round decimals
- bin(n).count('1') to count set bits
- x & (x - 1) == 0 checks power of 2
- x ^ y for bit toggling
- x & 1 for odd/even
- itertools.permutations(arr) for permutations
- itertools.combinations(arr, r) for combos
- itertools.product(a, b) for Cartesian product
- itertools.accumulate(arr) for prefix sums
- math.comb(n, r) for nCr
Recursion & DP
- @lru_cache(maxsize=None) for memoization
- Always define base cases in recursion
- Avoid mutable default args in recursion
- Use tuple in memo keys instead of list
- Convert top-down to bottom-up if recursion is deep
- Use 2D/3D lists for DP
- [[-1]*cols for _ in range(rows)] for DP init
- Use directions = [(0,1),(1,0),(0,-1),(-1,0)] for grid problems
- float('inf') as initial value
- Rolling array for 1D DP space optimization
- Maintain parent pointers for path
- Dict for sparse DP state storage
- Convert recursive to iterative when needed
- Tabulate overlapping subproblems
- Trace DP state transitions clearly
Strings & Arrays
- arr[::-1] for reverse
- ' '.join(arr) to join strings
- s.split() to split string
- s.strip() to remove spaces
- s.startswith(), s.endswith() for prefix/suffix
- s.find(sub), s.index(sub) for substring
- s.count(char) for char frequency
- collections.Counter(s) for string frequency
- ord(char), chr(code) for ASCII
- Sliding window for substrings
- Prefix sums for range queries
- Hashmap for subarray sum problems
- Sort + two-pointer for pair sum
- set comparison for anagram check
- ''.join(reversed(s)) for reversed string
Algorithm Design Tricks
- Binary search on sorted + predicate
- BFS for shortest path (unweighted graph)
- DFS for traversal and cycle detection
- Union-Find for connected components
- Topological Sort for dependency graphs
- Bitmasking for subset state DP
- Sliding Window for fixed-size subarrays
- Two Pointer for sorted array operations
- Monotonic Stack for nearest greater/smaller
- Trie for prefix string problems
Debugging & Efficiency
- print(*arr) to pretty print
- breakpoint() or pdb.set_trace() for debug
- Use time.time() or timeit to measure time
- Avoid pop(0) on list - use deque instead
- Use try-except wisely
- Avoid global vars in functions
- Avoid unnecessary sorting
- Always check constraints first
- Use PyPy if allowed for speed
- Think in terms of complexity (time/space)