Python Algorithm Template

Two Pointer (Opposite Direction)

def two_pointers_opposite(arr):
    left, right = 0, len(arr) - 1
    while left < right:
        # Process current elements
        current = process(arr[left], arr[right])
        
        # Update pointers based on condition
        if condition(arr[left], arr[right]):
            left += 1
        else:
            right -= 1

Same Direction

def two_pointers_same(arr):
    slow, fast = 0, 0
    while fast < len(arr):
        # Process current elements
        current = process(arr[slow], arr[fast])
        
        # Update pointers based on condition
        if condition(arr[slow], arr[fast]):
            slow += 1
        
        # Fast pointer always moves forward
        fast += 1

DFS in Graph

DFS in Graph using Stack

DFS in Tree

DFS in Tree using Stack

DFS Backtracing

DFS Backtracing Aggregation

BFS on Graph

BFS on Tree

Prefix Tree

Union-Find

More Tree

iterative (stack-based) DFS for preorder, inorder, and postorder traversals.

🌳 1️⃣ Preorder (Root β†’ Left β†’ Right)

🌿 2️⃣ Inorder (Left β†’ Root β†’ Right)

🌲 3️⃣ Postorder (Left β†’ Right β†’ Root)

πŸ…° Using Two Stacks (Simplest)

πŸ…± Using One Stack (More Compact)


🧠 Unified DFS Recursion

🌳 Unified Stack-Based Template

Last updated