Python Cheat Sheet for LeetCode

LeetCode is a popular platform for practicing coding problems and preparing for technical interviews. I’ve created this cheat sheet to help quickly reference common data structures, algorithms, and Python APIs used in LeetCode problems.


Lists

1
2
3
4
5
6
7
8
9
10
myList = [1, 'abc']  # lists can contain different data types

myList.append(1) # add element to the end
myList.index(1) # return index of first occurrence
myList.insert(0, 3) # insert 3 at index 0
myList.remove(1) # remove first occurrence of 1
myList.pop() # remove last element
myList.pop(0) # remove element at index 0
myList.sort() # sort list
myList.reverse() # reverse list

Useful Tricks

1
2
3
4
5
6
7
8
9
10
# slicing
nums = [1, 2, 3, 4]
nums[1:3] # [2, 3]

# iterate with index
for i, val in enumerate(nums):
print(i, val)

# list comprehension
squares = [x*x for x in nums]

Dictionary (dict)

1
2
3
4
5
6
7
8
9
myDict = {'a': 1, 'b': 2}

myDict['a'] # access value
myDict.get('c', 0) # safe access with default
myDict['c'] = 3 # add/update
del myDict['a'] # delete key

for k, v in myDict.items():
print(k, v)

Set

1
2
3
4
5
6
7
8
mySet = {1, 2, 3}

mySet.add(4)
mySet.remove(1) # error if not exist
mySet.discard(10) # safe remove

if 2 in mySet:
print("exists")

Counter

1
2
3
4
5
6
from collections import Counter

cnt = Counter([1, 1, 2, 3])

cnt[1] # 2
cnt.most_common(1) # [(1, 2)]

Deque

1
2
3
4
5
6
7
8
from collections import deque

dq = deque([1, 2, 3])

dq.append(4) # add right
dq.appendleft(0) # add left
dq.pop() # remove right
dq.popleft() # remove left

Heap (Priority Queue)

1
2
3
4
5
6
7
8
9
import heapq

heap = []

heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 2)

heapq.heappop(heap) # 1 (smallest)

Final Tips

  • Use list for most problems

  • Use set/dict for O(1) lookup

  • Use deque for BFS

  • Use heapq for top K problems

  • Use Counter for frequency problems