Python Leetcode CheatSheet
Use len to find size of all of these
Use len(x) = 0 for isEmpty
1. Array / List
arr = [0] * 10 # array of 10 zeros
arr = [1, 2, 3] # create
[Link](4) # add to end
[Link]() # remove last
arr[1] # access index
arr[1:3] # slicing
len(arr) # size
2. Stack (use list)
stack = []
[Link](10) # push
[Link]() # pop
stack[-1] # peek
3. Queue / Deque
from collections import deque
q = deque()
[Link](1) # enqueue
[Link]() # dequeue
[Link](2) # add to front
[Link]() # remove from back
4. Priority Queue / Min Heap
import heapq
heap = []
[Link](heap, 5) # push
[Link](heap, (2, "a")) # tuple (sorted by first elem)
smallest = heapq[0] # peek
val = [Link](heap) # pop min
[Link](range(n)) # heapifies a list
Max heap trick:
[Link](heap, -val)
max_val = -[Link](heap)
5. HashSet
s = set()
[Link](1)
1 in s # check membership
[Link](1) # remove
[Link](5) # safe remove (no error if not present)
6. HashMap / Dictionary
d = {}
d["a"] = 10
[Link]("a", 0) # get with default
"a" in d # check key
del d["a"] # delete key
[Link]("a") # remove key and return value, error if missing
[Link]("b", 0) # remove key and return value, default if missing
7. Counter / Frequency Map
from collections import Counter
freq = Counter([1,1,2,3])
freq[1] # count of 1 → 2
freq[2] += 3 # increment count of 2
freq.most_common(1) # top 1 element
[Link](1) # remove key and return count, error if missing
[Link](1, 0) # remove key and return count, 0 if missing
for key, count in [Link]():
print(key, count)
8. DefaultDict
from collections import defaultdict
graph = defaultdict(list)
graph[0].append(1) # auto-init empty list if key not present
del graph[0] # delete key
[Link](1) # remove key and return value, error if missing
[Link](1, []) # remove key and return value, [] if missing
Can also use for other defaults: defaultdict(int) , defaultdict(set) , etc.
9. SortedList (from sortedcontainers)
from sortedcontainers import SortedList
sl = SortedList([3,1,2])
[Link](4) # insert element → maintains sorted order
[Link](2) # remove element
[Link](0) # pop smallest
[Link](-1) # pop largest
sl[0] # access smallest
sl[-1] # access largest
len(sl) # size
sl.bisect_left(3) # index to insert 3 on the left
sl.bisect_right(3) # index to insert 3 on the right
{} vs []
Structure Syntax Ordered Duplicates Access Use Cases
Allowed
List [] Yes Yes Index Stack, Queue,
Sequence
Dict {} Yes Keys No, Values Key Frequency maps,
Yes Graphs
Set set() No No N/A Membership,
Deduplication
Sorting an array
# python sort is O(nlogn) and stable
# in place
[Link]()
[Link](reverse=True)
# new copy
sarr = sorted(arr)
sarr = sorted(arr, reverse=True)
# with key function
[Link](key=abs) # key must be a lambda that returns a value to sort by
Avoiding string concat
chars = []
[Link](["a"] * 5)
[Link]("a" * 5) # faster
"".join(chars)
"".join(reversed(chars))
Bit Manipulation
n = 13 # 0b1101
# --- Basic ops ---
n & 1 # get rightmost bit
n | 1 # set last bit
n ^ 1 # toggle last bit
~n # bitwise NOT
n << 1 # shift left (multiply by 2)
n >> 1 # shift right (floor divide by 2)
# --- Check / manipulate specific bits ---
i = 2
(n >> i) & 1 # check i-th bit
n |= (1 << i) # set i-th bit
n &= ~(1 << i)# clear i-th bit
n ^= (1 << i) # toggle i-th bit
# --- Common tricks ---
n & (n-1) == 0 # is power of 2
rightmost = n & -n # isolate rightmost 1-bit
bin(n).count('1') # count number of 1-bits
# --- Reverse bits (32-bit example) ---
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1