Python LeetCode Tricks Every Engineer Should Use
2025-08-17
LeetCode in Python gives you shortcuts that can make your code both cleaner and faster to write. Many engineers miss these built-ins and patterns during interviews, which can cost precious time. Below are practical Python tricks every engineer should know when solving LeetCode problems.
1) Use Built-in Counters for Frequency Problems
Instead of writing manual loops, use collections.Counter
.
from collections import Counter
nums = [1,1,2,3,3,3,4]
freq = Counter(nums)
# Most common k elements
print(freq.most_common(2)) # [(3, 3), (1, 2)]
When useful: Top K Frequent Elements, Anagrams, Majority Element.
2) Multiple Assignment for Swaps and State Updates
Python lets you update values in one line without temp variables.
# Swap two values
a, b = b, a
# Fibonacci style DP
a, b = b, a + b
When useful: Climbing Stairs, House Robber, stock buy/sell DP.
3) Use Slicing and Negative Indexing
Python strings and arrays allow slicing shorthand.
s = "leetcode"
print(s[::-1]) # 'edocteel'
When useful: Palindrome checks, reversing arrays/strings.
4) Heapq for Priority Queues
Python’s heapq
implements min-heap. Push negatives for max-heap.
import heapq
nums = [5,3,8,1]
heapq.heapify(nums) # [1,3,8,5]
heapq.heappush(nums, 2) # push new item
print(heapq.heappop(nums)) # 1
When useful: Kth Largest Element, Meeting Rooms II, Merge K Lists.
5) Enumerate Instead of Range(len)
Cleaner loop with index and value together.
for i, val in enumerate([10,20,30]):
print(i, val)
When useful: Two Sum (with hashmap), array traversals.
6) Defaultdict to Simplify Maps
No need to check if key exists.
from collections import defaultdict
graph = defaultdict(list)
edges = [(0,1),(1,2),(2,3)]
for u,v in edges:
graph[u].append(v)
When useful: Graph adjacency lists, grouping problems.
7) Zip for Pair Iteration
Compact way to iterate over multiple arrays.
nums = [1,2,3]
squares = [1,4,9]
for n, sq in zip(nums, squares):
print(n, sq)
When useful: Merge intervals, processing two lists at once.
8) Any / All for Boolean Checks
nums = [2,4,6]
print(all(x % 2 == 0 for x in nums)) # True
print(any(x > 5 for x in nums)) # True
When useful: Validation problems, checking constraints in one line.
9) Sorted with Key Functions
words = ["apple","banana","kiwi"]
print(sorted(words, key=len)) # ['kiwi','apple','banana']
When useful: Interval problems, custom sorting logic.
10) Using @lru_cache
for Memoization
from functools import lru_cache
@lru_cache(None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
print(fib(30)) # fast thanks to cache
When useful: DP/backtracking problems like Word Break, Decode Ways.
11) Pythonic BFS/DFS with Deque
from collections import deque
q = deque([0])
while q:
node = q.popleft()
# process node
for nei in graph[node]:
q.append(nei)
When useful: Graph traversal, shortest path problems.
12) Use Bisect for Binary Search
import bisect
arr = [1,3,5,7]
i = bisect.bisect_left(arr, 5) # index 2
When useful: Lower/upper bound problems, insert position.
13) List Comprehensions for Concise Construction
matrix = [[0]*3 for _ in range(3)]
evens = [x for x in range(10) if x%2==0]
When useful: Building grids, filtering lists on the fly.
14) String Join for Fast Concatenation
words = ["leet","code"]
print("".join(words)) # 'leetcode'
When useful: Building results in backtracking, string operations.
15) Use Sets for Fast Lookups
nums = [1,2,3,4]
target = 5
seen = set()
for n in nums:
if target-n in seen: print("Found")
seen.add(n)
When useful: Two Sum, subsequence problems, deduplication.
Interview Checklist for Python on LeetCode
- Do I need Counter or defaultdict for counting/grouping?
- Can I replace loops with any/all checks?
- Is heapq better than sorting every time?
- Would bisect simplify binary search?
- Should I memoize recursion with @lru_cache?
Final Note
These Python tricks won’t just save you keystrokes — they save time in an interview, reduce bugs, and make your code stand out as elegant.
If you want to see clean Python LeetCode solutions with explanations while practicing, check out StealthCoder. It can overlay step-by-step solutions in real time so you can focus on learning the patterns.