0% found this document useful (0 votes)
12 views2 pages

Python DSA CheatSheet

Uploaded by

Akarsh Chaudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Python DSA CheatSheet

Uploaded by

Akarsh Chaudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Ultimate Python DSA Cheat Sheet

1. Arrays / Lists
len(arr), sum(arr), max(arr), min(arr), sorted(arr), reversed(arr)
enumerate(arr): Get (index, value)
zip(arr1, arr2): Pair-wise combine
arr[::-1]: Reverse a list
[i for i in arr if i > 0]: List comprehension

2. Hash Maps / Frequency Count


from collections import Counter, defaultdict
Counter(arr): Frequency dict
defaultdict(int): Auto-init to 0
[Link](key, default): Safe get

3. Strings
' '.join(list_of_strings): Join with separator
[Link](): Split on space
[Link](): Trim ends
ord('a'), chr(97): ASCII conversions
s[::-1]: Reverse string

4. Stack / Queue
stack = []; [Link](x); [Link]()
from collections import deque
q = deque(); [Link](x); [Link]()

5. Heap / Priority Queue


import heapq
[Link](arr): Min-heap
[Link](heap, x), [Link](heap)
Max heap: Push (-val, val) or invert manually
[Link](k, arr), [Link](k, arr)

6. Binary Search
from bisect import bisect_left, bisect_right
bisect_left(arr, x): First pos to insert x
bisect_right(arr, x): Last pos to insert x

7. Recursion / Backtracking
def dfs(i):
if base_case: return
for choice in choices:
dfs(i+1)

8. Dynamic Programming
# Top-down (memoization)
from functools import lru_cache
@lru_cache(None)
def dp(i): return max(dp(i-1), ...)
# Bottom-up
dp = [0] * n; dp[0] = base
for i in range(1, n): dp[i] = ...

9. Trees / Graphs
# Tree Traversal
def dfs(node):
if not node: return
dfs([Link]); dfs([Link])
# BFS
from collections import deque
q = deque([root])
while q: node = [Link]()
# Union Find
parent = list(range(n))
def find(x): if parent[x] != x: parent[x] = find(parent[x]); return parent[x]
def union(x, y): parent[find(x)] = find(y)

10. Combinatorics / Math / Bit


from math import gcd, comb, factorial
a & b, a | b, a ^ b: Bitwise AND/OR/XOR
x << 1 (multiply by 2), x >> 1 (divide by 2)
bin(x).count('1'): Count set bits

11. Common Patterns


# Sliding Window
l = 0; for r in range(n): while condition: l += 1
# Two Pointers
i, j = 0, n-1; while i < j: ...
# Prefix Sum
prefix = [0]*(n+1); prefix[i+1] = prefix[i] + arr[i]
# Kadane's Algo (Max Subarray)
cur_sum = max_sum = arr[0]
for num in arr[1:]: cur_sum = max(num, cur_sum + num)
max_sum = max(max_sum, cur_sum)

You might also like