20+ Templates To Half The Time You Spend On Leetcode Problems

If you’ve spent any amount of time grinding through Leetcode, HackerRank, or similar sites, you’ve probably noticed something:


A lot of problems follow the same core patterns.

It’s something that I’ve talked about before. And now that I’ve also covered what the algorithms are and how they work, I want to finish off this trilogy by giving you a template bank for the most common patterns.

In this post, you’ll find 20+ Python templates for the most frequently tested algorithms and data structures. Use them to skip the boilerplate and spend your brainpower on the problem-specific logic!

1. Searching & SortingBinary Search (Iterative)

def binary_search(arr, target):

    left, right = 0, len(arr) – 1

    while left <= right:

        mid = (left + right) // 2

        if arr[mid] == target:

            return mid

        elif arr[mid] < target:

            left = mid + 1

        else:

            right = mid – 1

    return -1

Binary Search (on Answer / Monotonic Condition)

def condition(x):

    # Define condition logic (True/False)

    return True

def binary_search_answer(low, high):

    while low < high:

        mid = (low + high) // 2

        if condition(mid):

            high = mid

        else:

            low = mid + 1

    return low

Sorting with Custom Key

arr = [(1, ‘b’), (2, ‘a’), (1, ‘a’)]

arr.sort(key=lambda x: (x[0], x[1]))  # Sort by multiple keys

2. Data StructuresStack

stack = []

stack.append(1)   # push

top = stack.pop() # pop

Queue (FIFO)

from collections import deque

q = deque()

q.append(1)     # enqueue

x = q.popleft() # dequeue

Priority Queue / Heap

import heapq

heap = []

heapq.heappush(heap, (priority, value))

priority, value = heapq.heappop(heap)

Hash Map

my_map = {}

my_map[‘key’] = ‘value’

for k, v in my_map.items():

    pass

Linked List Node

class ListNode:

    def __init__(self, val=0, next=None):

        self.val = val

        self.next = next

3. Graph TraversalDFS (Recursive)

def dfs(node, visited, graph):

    if node in visited:

        return

    visited.add(node)

    for nei in graph[node]:

        dfs(nei, visited, graph)

DFS (Iterative)

def dfs_iterative(start, graph):

    stack = [start]

    visited = set()

    while stack:

        node = stack.pop()

        if node not in visited:

            visited.add(node)

            stack.extend(graph[node])

BFS

from collections import deque

def bfs(start, graph):

    q = deque([start])

    visited = set([start])

    while q:

        node = q.popleft()

        for nei in graph[node]:

            if nei not in visited:

                visited.add(nei)

                q.append(nei)

Dijkstra’s Algorithm

import heapq

def dijkstra(graph, start):

    dist = {node: float(‘inf’) for node in graph}

    dist[start] = 0

    heap = [(0, start)]

    while heap:

        d, node = heapq.heappop(heap)

        if d > dist[node]:

            continue

        for nei, weight in graph[node]:

            new_dist = d + weight

            if new_dist < dist[nei]:

                dist[nei] = new_dist

                heapq.heappush(heap, (new_dist, nei))

    return dist

4. Dynamic Programming (DP)1D DP

def dp_1d(n):

    dp = [0] * (n + 1)

    dp[0] = 1

    for i in range(1, n + 1):

        dp[i] = dp[i – 1] + 1  # example transition

    return dp[n]

2D DP

def dp_2d(rows, cols):

    dp = [[0] * cols for _ in range(rows)]

    dp[0][0] = 1

    for r in range(rows):

        for c in range(cols):

            if r > 0:

                dp[r][c] += dp[r – 1][c]

            if c > 0:

                dp[r][c] += dp[r][c – 1]

    return dp[rows – 1][cols – 1]

Memoization (Top-Down)

from functools import lru_cache

@lru_cache(None)

def solve(i):

    if i == 0:

        return 1

    return solve(i – 1) + 1  # example

5. StringsReverse String

s = “hello”

s_rev = s[::-1]

Check Palindrome

def is_palindrome(s):

    return s == s[::-1]

Sliding Window

def sliding_window(s, k):

    count = {}

    left = 0

    for right in range(len(s)):

        count[s[right]] = count.get(s[right], 0) + 1

        if right – left + 1 > k:

            count[s[left]] -= 1

            if count[s[left]] == 0:

                del count[s[left]]

            left += 1

6. TreesBinary Tree Node

class TreeNode:

    def __init__(self, val=0, left=None, right=None):

        self.val = val

        self.left = left

        self.right = right

DFS (Preorder Traversal)

def preorder(root):

    if not root:

        return

    print(root.val)

    preorder(root.left)

    preorder(root.right)

BFS (Level Order Traversal)

from collections import deque

def level_order(root):

    if not root:

        return

    q = deque([root])

    while q:

        node = q.popleft()

        print(node.val)

        if node.left:

            q.append(node.left)

        if node.right:

            q.append(node.right)

How To Use This Bank EffectivelyPattern Recognition is Key – Before pasting a template, ask yourself which pattern this problem fits. Is it BFS, sliding window, or DP? Use our other post for help on that!
Adapt, Don’t Adopt Blindly – These templates save you from retyping the basics, but you still need to tailor them to the exact problem constraints.
Memorize the Templates – In interviews, you won’t have access to this template file. What you can do instead is map our “algorithm heuristics” to these boilerplates, and make Anki cards out of them so you know exactly what to do and when. Would you be interested in using flashcards like these? Let us know!

📌 Final Tip:
Keep this post open in a split view while practicing. Over time, you’ll memorize the patterns naturally, and your fingers will type them out before you even think about them!

The post 20+ Templates To Half The Time You Spend On Leetcode Problems appeared first on Jacob Robinson.

 •  0 comments  •  flag
Share on Twitter
Published on August 16, 2025 08:00
No comments have been added yet.