🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Algorithms: Binary Search, Graphs, and Dynamic Programming

Python AlgorithmsđŸŸĸ Free Lesson

Prerequisites

  • !Big-O analysis and log-linear reasoning
  • !Recursion, queues, and Python dictionaries

What You'll Learn

  • 1Maintain the loop invariant that keeps binary search correct
  • 2Pick BFS or DFS based on what the problem needs, not habit
  • 3Translate a recursive relation into a bottom-up dynamic program
  • 4Read a complexity table and choose the right tool for the input size
  • 5Test algorithms against adversarial and degenerate inputs

Interviews and production code both reward the same skill: choosing an algorithm whose cost matches the input you actually receive, and implementing it without boundary bugs. Three families cover most day-to-day work — binary search over ordered data, breadth and depth first traversal over graphs, and dynamic programming over problems with overlapping subproblems. This lesson gives you implementations you can trust plus the invariants that explain why they are correct.

Binary search is an invariant, not a formula

The classic loop is short enough to rewrite from memory, which is exactly why people get it wrong. The safety lies in one invariant: if the target exists, its index always lies inside the half-open window between lo and hi. Every branch must preserve that claim.

python
def binary_search(items, target):
    lo, hi = 0, len(items)
    while lo < hi:
        mid = (lo + hi) // 2
        if items[mid] == target:
            return mid
        if items[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return -1


def lower_bound(items, target):
    """First index whose value is >= target, or len(items)."""
    lo, hi = 0, len(items)
    while lo < hi:
        mid = (lo + hi) // 2
        if items[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo


data = [1, 3, 3, 5, 8, 13]
print(binary_search(data, 8))        # 4
print(binary_search(data, 4))        # -1
print(lower_bound(data, 3))          # 1 (first occurrence)
print(lower_bound(data, 6))          # 4 (insertion point)

Using hi = len(items) and the strict lo < hi condition removes both the empty-input crash and the infinite loop that appear when the window is closed and the pointer updates are inconsistent. The second function is the more useful one in practice: duplicate keys, ranges, and "insert here" questions all reduce to finding a boundary rather than an exact match. Python ships this as bisect.bisect_left, and it is worth reading its source once.

Breadth, depth, and what each one promises

Graphs in Python are almost always dictionaries mapping a node to its neighbours. Both traversals walk that structure; they differ in the order, and the order determines what you learn.

python
from collections import defaultdict, deque

def build_graph(edges):
    graph = defaultdict(list)
    for u, v in edges:
        graph[u].append(v)
        graph[v].append(u)
    return graph

def bfs(graph, start):
    seen = {start}
    queue = deque([start])
    order = []
    parent = {start: None}
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbour in graph[node]:
            if neighbour not in seen:
                seen.add(neighbour)
                parent[neighbour] = node
                queue.append(neighbour)
    return order, parent

def dfs(graph, start, seen=None, order=None):
    seen = {start} if seen is None else seen
    order = [] if order is None else order
    seen.add(start)
    order.append(start)
    for neighbour in graph[start]:
        if neighbour not in seen:
            dfs(graph, neighbour, seen, order)
    return order

g = build_graph([(0, 1), (0, 2), (1, 2), (2, 3), (3, 4)])
print(bfs(g, 0)[0])      # [0, 1, 2, 3, 4]
print(dfs(g, 0))         # [0, 1, 2, 3, 4]

Breadth first search gives you the shortest path in an unweighted graph because it explores by distance layers, and the parent map it builds is enough to reconstruct that path. Depth first search uses less bookkeeping and is the natural shape for cycle detection, topological sorting, and exhaustive search. Note the Python-specific trap: the recursive DFS above is fine for a few thousand nodes, but a deep chain will hit the recursion limit, so long graphs want an explicit stack.

From recurrence to table: dynamic programming by hand

Dynamic programming is recursion plus two observations: the subproblems overlap, and you can order them so each answer is computed once. Start by writing the recurrence, then fill a table in an order where every dependency is already solved.

python
def knapsack(weights, values, capacity):
    n = len(weights)
    dp = [[0] * (capacity + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        w, v = weights[i - 1], values[i - 1]
        for limit in range(capacity + 1):
            dp[i][limit] = dp[i - 1][limit]
            if w <= limit:
                take = dp[i - 1][limit - w] + v
                if take > dp[i][limit]:
                    dp[i][limit] = take

    return dp[n][capacity], reconstruct(dp, weights, capacity)


def reconstruct(dp, weights, capacity):
    chosen = []
    i, limit = len(weights), capacity
    while i > 0 and limit >= 0:
        if dp[i][limit] != dp[i - 1][limit]:
            chosen.append(i - 1)
            limit -= weights[i - 1]
        i -= 1
    return chosen[::-1]


print(knapsack([2, 3, 4, 5], [3, 4, 5, 6], 8))
# (10, [1, 3])

Building the reconstruction path is the part people skip and then regret: a table that only stores the best value cannot tell you which items produced it. The two-dimensional shape makes the state explicit — first i items, remaining capacity limit — and once that is clear, you can compress the outer dimension to a single row when memory matters, at the cost of losing reconstruction.

A complexity cheat sheet for everyday choices

Problem size nFeasible with n log nFeasible with n squaredExponential is hopeless
10 to 100AnythingAnythingSometimes
1,000AnythingFine in PythonOnly with heavy pruning
100,000Standard choiceUsually too slowNo
10,000,000Needs arrays and NumPyNoNo
1,000,000,000Needs approximationsNoNo

Use the table before writing code. If the input can reach a hundred thousand rows and your first idea is nested loops, you have already decided the answer; switch to sorting, hashing, or a linear scan with a smarter invariant. Hashing deserves special emphasis: dictionaries and sets make many quadratic problems linear, which is why most Python solutions are O(n) with enough memory.

Testing algorithms where they break

Correct-looking code fails on boundaries, so generate tests that target them. Binary search wants an empty list, a single element, duplicates, an absent target below the minimum and above the maximum. Traversals want a disconnected graph, a cycle, a self-loop, and a chain long enough to expose recursion depth. Dynamic programs want zero capacity, zero items, items heavier than the bag, and a case where greedy selection loses so your optimum differs from the naive answer.

A useful habit is to compare your implementation against a slow brute-force reference on thousands of small random inputs. A binary search checked against list.index, a knapsack checked against the exponential search, and a traversal checked against a set-based walk will catch ordering mistakes that hand-picked examples never reach.

Shortest paths as soon as weights appear

Breadth first search answers shortest path only when every hop costs the same. Introduce weighted edges and the layer-by-layer promise breaks, because a path with more edges can still be cheaper. Dijkstra's algorithm restores the guarantee by always expanding the unsettled node with the smallest known distance, and a binary heap makes that selection logarithmic instead of linear. The one precondition is non-negative weights: a negative edge can shorten a distance after a node has been settled, which invalidates the whole argument. If negative weights are possible, switch to Bellman-Ford and accept the higher cost.

The implementation detail that trips people up is the stale entry. When you relax an edge you may push a better distance into the heap while an older, worse one is still sitting there, so the pop can return a distance that is no longer current. The cheap fix is to discard any popped entry whose distance is larger than the best known value for that node, rather than trying to decrease a key inside the heap. Keeping the heap small this way is both simpler and faster than maintaining an index of positions.

Traversal familyEdge assumptionCost with a heapWhat it tells you
BFSUnweightedLinear in vertices and edgesFewest hops
DijkstraNon-negative weightsLog-linearCheapest total cost
Bellman-FordNegative weights allowedQuadraticCheapest cost or a negative cycle
A starWeights plus a heuristicDepends on heuristic qualityCheapest path with guidance

Greedy, divide and conquer, or dynamic programming

Three templates cover most problems, and the choice comes from one question: does an optimal solution contain optimal solutions to smaller versions of itself? If yes and the subproblems overlap, you want dynamic programming. If yes and the pieces are independent, divide and conquer fits. If a locally best choice always leads to a globally best answer, greedy is enough, but greedy is the one that needs a proof because it fails quietly on problems that look similar.

Building that instinct takes practice, so work the contrasts deliberately. Scheduling by earliest finishing time is greedy and provably optimal for maximising non-overlapping jobs. Selecting a set of jobs under a knapsack constraint is not, because a locally valuable item can block two better ones. Coin change with canonical denominations can be greedy, yet the same problem with arbitrary denominations needs dynamic programming. When you cannot produce the proof in a few sentences, assume the greedy version is wrong and write a brute-force oracle to check it on small inputs.

Common Mistakes

Applying breadth first search to a graph with meaningful edge weights

Fix: Use Dijkstra for non-negative weights or Bellman-Ford when negative edges exist.

Mixing an inclusive hi with lo less than or equal to hi and an off-by-one update

Fix: Standardise on a half-open window with hi = len(items) and lo less than hi, and never change only one side.

Using recursion for DFS on large or deep graphs

Fix: Iterate with an explicit stack, or raise limits only after confirming the depth is genuinely bounded.

Writing the knapsack value table but never the reconstruction step

Fix: Store enough state, or walk the table backwards comparing rows, to recover the chosen items.

Reaching for greedy whenever dynamic programming appears

Fix: Prove the greedy choice property with a counterexample attempt before trusting it.

Best Practices

  • State the invariant of a search loop in a comment next to the condition
  • Wrap standard library helpers such as bisect and heapq when you need named semantics
  • Keep graph construction separate from traversal so both can be tested independently
  • Comment the meaning of every dynamic programming cell index such as dp[i][limit]
  • Benchmark against a brute-force oracle on random small inputs before shipping

Key Takeaways

  • Binary search is correct because of a preserved window invariant, not because of the midpoint trick
  • BFS promises shortest unweighted paths; DFS promises simple exhaustive exploration
  • Dynamic programming is a recurrence plus an evaluation order that computes each state once
  • Hash-based structures convert many quadratic approaches into linear ones in Python
  • Boundary-focused tests and brute-force oracles catch the mistakes that examples miss
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement