Comprehensive Collection of Algorithm Templates and Code Snippets for LeetCode
This guide compiles essential Python built‑in functions, data‑structure utilities, and ready‑to‑use algorithmic templates—including dynamic programming, backtracking with caching, binary search, bit manipulation, union‑find, topological sort, monotonic stack, sliding window, prefix sums, two‑pointer and graph traversals—to accelerate LeetCode problem solving.
This document provides a curated set of Python built‑in functions, data‑structure utilities, and algorithmic templates frequently used to solve LeetCode problems.
Common Python utilities include reduce , functools.lru_cache , filter , divmod , and string/collection methods such as split , strip , join , replace , startswith , endswith , as well as deque operations.
reduce(function, iterable[, initializer])
reduce(lambda x,y:x * y, ns) # product of array
reduce(lambda x,y:x + y, ns) # sum of array
@functools.lru_cache(None)
res = helper(0, N, 0)
helper.cache_clear()Data‑structure operations for deque , list , dict , set , and heapq are listed, showing methods such as append , appendleft , pop , popleft , heapify , heappush , and heappop .
queue = deque([iterable, maxlen])
queue.append(val)
queue.appendleft(val)
queue.pop()
queue.popleft()Several algorithmic patterns are presented:
Dynamic programming templates for 0‑1 knapsack, complete knapsack, and state‑transition formulas.
Backtracking with pruning using functools.lru_cache and visited arrays.
Binary search (left/right boundaries, insertion point).
Bit manipulation for masks, parity checks, and power‑of‑two tests.
Union‑Find (disjoint set) with path compression and union by size.
Topological sorting using indegree arrays and BFS.
Monotonic stack for maximum rectangle, rain‑water trapping, and daily temperatures.
Sliding window for substring search and fixed‑size window problems.
Prefix‑sum techniques for subarray sums, matrix sums, and counting problems.
Two‑pointer technique for in‑place array modifications.
Graph traversals (BFS/DFS) and Dijkstra/Floyd shortest‑path algorithms.
Representative code snippets are kept intact within ... blocks.
# 0‑1 knapsack
for n in ns:
for i in range(T, n-1, -1):
dp[i] = max(dp[i], dp[i-n] + ws[i])
# Backtracking with pruning
@functools.lru_cache(None)
def backtrack(path, choices):
if condition:
results.append(path)
return
for choice in choices:
if visited[choice]:
continue
backtrack(path+[choice], new_choices)
# Binary search left boundary
while L <= R:
M = (L+R)//2
if nums[M] < target:
L = M+1
else:
R = M-1
# Union‑Find
parent = {}
size = collections.defaultdict(lambda:1)
def find(x):
while x != parent.setdefault(x, x):
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]These templates serve as a quick reference for developers preparing for coding interviews or competitive programming contests.
DaTaobao Tech
Official account of DaTaobao Technology
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.