Common Bugs in Algorithm Code and How to Catch Them
An algorithm can be right on paper and wrong in code. The gap is usually not a deep misunderstanding but one of a handful of small, repeatable mistakes: a loop bound off by one, an empty list nobody thought about, two variables that turn out to be the same list. This guide collects the common ones, shows each with a short run, and ends with the testing habit that catches most of what is left. Examples use Python 3.10 or later and only the standard library.
Off-by-one errors
Python's range(a, b) includes a and excludes b. Forgetting that is the classic off-by-one:
def sum_to(n):
total = 0
for i in range(1, n): # bug: stops at n - 1
total += i
return total
def sum_to_fixed(n):
return sum(range(1, n + 1)) # range's end is exclusive
print(sum_to(10), sum_to_fixed(10))
45 55
The buggy version adds 1 to 9 and returns 45 instead of 55. The same mistake hides in slices (s[i:j] excludes j), in loops that compare i < n where i <= n was meant, and above all in binary search, where the choice between lo < hi and lo <= hi and between mid and mid - 1 must match the loop invariant; see binary search.
How to spot it: test the smallest inputs, where an off-by-one changes the answer by a whole element. For a loop, check the first and last iteration by hand: which index does it start at, and which is the last one it touches?
Empty and single-element inputs
Code that reads nums[0] or nums[-1] assumes the list has at least one item:
def largest(nums):
best = nums[0] # fails on an empty list
for x in nums[1:]:
if x > best:
best = x
return best
for case in ([3, 1, 2], [7], []):
try:
print(case, largest(case))
except IndexError as err:
print(case, "IndexError:", err)
[3, 1, 2] 3
[7] 7
[] IndexError: list index out of range
Decide what an empty input should produce (an exception with a clear message, None, or a default) and handle it explicitly at the top of the function. Python's built-in max([]) raises ValueError, and max([], default=None) returns None. Single-element inputs deserve their own test too: a two-pointer loop with lo < hi never runs on one element, which may or may not be what you want.
Duplicates
Many algorithms are written with distinct values in mind and break on repeats. A binary search that returns "an index of the target" is not the same as one that returns "the first index" when the target appears several times. A pair-sum check that adds each value to a set before looking up its complement will pair an element with itself. Writing >= where > was meant, or the reverse, can make an insertion sort unstable or a loop stop one step early. Whenever a problem allows duplicates, put an all-equal input in your tests.
Integer division and float comparison
import math
print(0.1 + 0.2 == 0.3)
print(0.1 + 0.2)
print(math.isclose(0.1 + 0.2, 0.3))
print(7 // 2, -7 // 2, int(-7 / 2))
print(7 / 2)
False
0.30000000000000004
True
3 -4 -3
3.5
Two separate traps:
- Floats are not exact. 0.1 and 0.2 have no exact binary representation, so their sum is 0.30000000000000004 and
==with 0.3 isFalse. Compare with a tolerance (math.isclose), or avoid floats entirely: count in integer cents, or usefractions.Fractionwhen you need exact ratios. //rounds toward negative infinity.-7 // 2is -4, whileint(-7 / 2)truncates toward zero and gives -3. Languages differ here, so code translated from C or Java can change behavior on negative numbers. Also,/always returns a float in Python 3, somid = (lo + hi) / 2produces a float that cannot be used as an index.
Aliasing: [[0] * n] * m
Multiplying a list copies references, not objects. For a list of numbers that does not matter, because integers are immutable. For a list of lists it does:
grid = [[0] * 3] * 2
grid[0][0] = 1
print(grid)
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid)
[[1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0]]
The first grid is two references to the same inner list, so setting one cell changes "both rows". This is a common source of wrong DP tables. Build 2-D lists with a comprehension, which creates a new inner list on each iteration. The same aliasing appears when you append a list to a results list and keep modifying it; in backtracking, store list(current), not current.
Mutating a list while iterating over it
nums = [2, 4, 6, 7]
for x in nums:
if x % 2 == 0:
nums.remove(x) # bug: the loop skips the item after each removal
print(nums)
nums = [2, 4, 6, 7]
nums = [x for x in nums if x % 2 != 0]
print(nums)
[4, 7]
[7]
The loop walks by index. Removing 2 shifts 4 into position 0, and the loop moves on to position 1, which now holds 6, so 4 is never examined. The result still contains an even number. Build a new list instead (a comprehension or filter), or loop over a copy (for x in nums[:]). Adding or deleting keys in a dict while iterating over it is caught by Python and raises RuntimeError; for lists there is no such guard.
Mutable default arguments
def add_item(item, bucket=[]): # bug: one list shared by every call
bucket.append(item)
return bucket
print(add_item(1))
print(add_item(2))
def add_item_fixed(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add_item_fixed(1))
print(add_item_fixed(2))
[1]
[1, 2]
[1]
[2]
A default value is evaluated once, when the function is defined, not on every call. So every call that relies on the default shares one list, and the second call sees the first call's item. This bites recursive helpers written as def helper(node, seen=set()): the second top-level call starts with a "seen" set full of stale entries. Use None as the default and create the object inside the function.
A missing or unreachable base case
import sys
def count_down(n):
if n == 0: # unreachable for odd n: n skips past 0
return "done"
return count_down(n - 2)
print(count_down(10))
print(sys.getrecursionlimit())
try:
count_down(9)
except RecursionError as err:
print("RecursionError:", err)
done
1000
RecursionError: maximum recursion depth exceeded
The base case exists, but odd inputs jump from 1 to -1 and never hit it, so the recursion runs until Python's recursion limit (1000 by default) stops it with RecursionError. Check that every recursive call moves strictly toward a base case for every valid input, and write the base case as a range (if n <= 0) when overshooting is possible.
A correct recursion can hit the same limit simply by being deep: a recursive sum of a 5,000-item list, or a DFS down a long path. Raising the limit is not a fix; rewrite deep recursions as loops. Recursion explained covers why.
Testing: compare against a brute force
Reading code for these bugs helps, but the habit that catches the most is mechanical:
- Write a slow, obviously correct version: a linear scan, every pair, every subset. It should be so simple that you trust it by reading it.
- Generate many small random inputs with a fixed
random.seed, so any failure can be reproduced exactly. Small sizes and a narrow value range force duplicates, empty lists and boundary cases to appear often. - Compare the two on every input, with
assertor by printing the first disagreement. - Shrink a failing case by hand: remove elements and change values while it still fails, until you reach the smallest input that shows the bug. That case usually explains itself.
Here is the method applied to a binary search for the first occurrence of a value, with a bug planted:
import random
def first_index(nums, target):
"""Index of the first occurrence of target in sorted nums, or -1."""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid # bug: may not be the FIRST occurrence
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
def first_index_slow(nums, target):
for i, x in enumerate(nums):
if x == target:
return i
return -1
random.seed(3)
for trial in range(1000):
nums = sorted(random.randint(0, 5) for _ in range(random.randint(0, 6)))
target = random.randint(0, 5)
if first_index(nums, target) != first_index_slow(nums, target):
print("trial", trial, "fails:", nums, target,
first_index(nums, target), first_index_slow(nums, target))
break
else:
print("no failure found")
# shrunk by hand to the smallest list that still fails
print("shrunk:", first_index([2, 2, 2], 2), first_index_slow([2, 2, 2], 2))
trial 33 fails: [1, 2, 2, 3, 4] 2 2 1
shrunk: 1 0
The random test finds a failure on its 34th input: in [1, 2, 2, 3, 4], the search lands on the second 2 and returns index 2, but the first 2 is at index 1. Shrinking by hand leads to [2, 2, 2], where the buggy version returns the middle index 1 instead of 0. The bug is now obvious: on a match, the search must keep looking to the left instead of returning. The fixed version remembers the match and continues with hi = mid - 1:
import random
def first_index(nums, target):
lo, hi = 0, len(nums) - 1
found = -1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
found = mid # remember it, keep looking to the left
hi = mid - 1
elif nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return found
def first_index_slow(nums, target):
for i, x in enumerate(nums):
if x == target:
return i
return -1
print(first_index([2, 2, 2], 2)) # the shrunk failing case
random.seed(3)
for trial in range(1000):
nums = sorted(random.randint(0, 5) for _ in range(random.randint(0, 6)))
target = random.randint(0, 5)
assert first_index(nums, target) == first_index_slow(nums, target), (nums, target)
print("1000 random cases agree")
0
1000 random cases agree
The same harness works for nearly any algorithm whose answer you can also compute slowly: sorting (compare with sorted), two-pointer and sliding-window code (compare with nested loops, as in two pointers and sliding window), DP (compare with exhaustive search on tiny inputs). It does not prove the fast version correct, but it finds most wrong ones in seconds.
A short checklist
- Empty input, one element, two elements.
- All values equal; values already sorted; values in reverse order.
- Negative numbers and zero; the largest allowed values.
- First and last iteration of every loop traced by hand.
- Every recursive call moves toward a base case.
- No list built with
*from inner lists, no mutable defaults, no mutation while iterating. - A brute-force comparison on random small inputs with a fixed seed.