Welcome to DRIXO — Your Coding Journey Starts Here
DRIXO Code • Learn • Build
DSA

Graph Algorithms: BFS and DFS Explained with Code

February 21, 2026 8 min read 0 Comments
Graph Algorithms: BFS and DFS Explained with Code
DSA

Graph Algorithms: BFS and DFS Explained with Code

DRIXO

Code · Learn · Build

Ready to level up your skills? In this comprehensive guide, we'll explore graph algorithms: bfs and dfs explained with code through practical examples. By the end, you'll have working code and deep understanding.

Understanding Graph Algorithms

Data structures and algorithms are the foundation of computer science. Let's explore graph algorithms with clear implementations.

# Graph Algorithms — Python implementation

def binary_search(arr, target):
    """
    Binary search in a sorted array.
    Time: O(log n) | Space: O(1)
    """
    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  # Not found

# Test
sorted_array = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print(f"Found 23 at index: {binary_search(sorted_array, 23)}")  # 5
print(f"Found 99 at index: {binary_search(sorted_array, 99)}")  # -1

Implementation Details

# Stack implementation
class Stack:
    def __init__(self):
        self._items = []

    def push(self, item):
        self._items.append(item)

    def pop(self):
        if self.is_empty():
            raise IndexError("Pop from empty stack")
        return self._items.pop()

    def peek(self):
        if self.is_empty():
            raise IndexError("Peek at empty stack")
        return self._items[-1]

    def is_empty(self):
        return len(self._items) == 0

    def size(self):
        return len(self._items)

# Practical use: balanced parentheses checker
def is_balanced(expression):
    stack = Stack()
    pairs = {')': '(', ']': '[', '}': '{'}

    for char in expression:
        if char in '([{':
            stack.push(char)
        elif char in ')]}':
            if stack.is_empty() or stack.pop() != pairs[char]:
                return False

    return stack.is_empty()

print(is_balanced("({[()]})"))   # True
print(is_balanced("({[()]}"))    # False
print(is_balanced(")("))         # False

Time and Space Complexity

AlgorithmBestAverageWorstSpace
Binary SearchO(1)O(log n)O(log n)O(1)
Quick SortO(n log n)O(n log n)O(n²)O(log n)
Merge SortO(n log n)O(n log n)O(n log n)O(n)
BFS/DFSO(V+E)O(V+E)O(V+E)O(V)

Practice Problems

Try these coding challenges to practice:

# Problem: Find two numbers that sum to target
def two_sum(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

print(two_sum([2, 7, 11, 15], 9))  # [0, 1] (2 + 7 = 9)

# Problem: Reverse a linked list
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverse_list(head):
    prev = None
    current = head
    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node
    return prev
AM
Arjun Mehta
Full-Stack Developer & Technical Writer at DRIXO

Full-stack developer with 5+ years of experience in Python and JavaScript. I love breaking down complex concepts into simple, practical tutorials. When I'm not coding, you'll find me contributing to open-source projects.

DSA

Comments