Sub topic 3
Pairs and Tuples with Nested Loops
Many brute-force solutions come down to one job: look at every pair, or every triple, of items and check each one against a condition. Nested loops are the simplest way to do that. They are also easy to get subtly wrong. A loop bound that is off by one can skip candidates, check an item against itself, or count the same pair twice.
This chapter assumes you can write Python functions and for loops, index into lists, and read basic Big-O notation. It also assumes you have already defined the search space for your problem. Here you will learn how to turn that search space into loops that visit each candidate exactly once.
Four Shapes of "Every Pair"
Before you write the loops, decide two things about the pairs you want:
- Does order matter? Ordered means
(i, j)and(j, i)are different candidates. Unordered means they are the same candidate and should be checked once. - Can an item pair with itself? If it can,
i == jis allowed. If it cannot, you must exclude it.
Those two answers give four shapes. Each one has its own loop bounds:
| Shape | Inner loop bounds | Candidates for n items | Typical problem |
|---|---|---|---|
| Ordered, self allowed | `for j in range(n)` | n² | All (row, column) cells of an n×n grid |
| Ordered, distinct | `for j in range(n)` with `if i == j: continue` | n(n−1) | "Does a send a message to b?" |
| Unordered, distinct | `for j in range(i + 1, n)` | n(n−1)/2 | Two-sum, closest pair, duplicate detection |
| Unordered, self allowed | `for j in range(i, n)` | n(n+1)/2 | "Can a number be the sum of two (possibly equal) squares?" |
The unordered, distinct shape is the most common one in algorithm problems. When the inner loop starts at i + 1, every pair i < j appears exactly once and no index meets itself. This halves the work compared with the n² shape. Halving does not change the Big-O class, but it removes a whole category of bugs.
The Canonical Example: Two-Sum
The two-sum problem works like this: given a list nums and a target, return the indices of two different elements that add up to target. The answer is a set of two indices, so order does not matter, and an element cannot be used twice. That makes it the unordered, distinct shape.
def two_sum_brute(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return (i, j)
return None
print(two_sum_brute([2, 7, 11, 15], 9)) # (0, 1)
print(two_sum_brute([3, 3], 6)) # (0, 1)
print(two_sum_brute([3], 6)) # None
print(two_sum_brute([], 0)) # NoneThe loops enumerate indices, not values. This matters when the list contains duplicates. In [3, 3] the two 3s are different elements, and only their indices can tell them apart.
The empty and single-element cases need no special code. When len(nums) is 0 or 1, the inner range is empty, so the function falls through to return None. Good loop bounds often handle edge cases on their own.
The value-loop trap
A common first attempt loops over values directly:
def two_sum_values_buggy(nums, target):
for x in nums:
for y in nums:
if x + y == target:
return (x, y)
return None
print(two_sum_values_buggy([3], 6)) # (3, 3) -- wrong: only one 3 exists
print(two_sum_values_buggy([1, 5], 6)) # (1, 5) -- right, by luckThis version has two bugs. It uses the ordered, self-allowed shape, so an element can pair with itself. It also returns values when the problem asked for indices. If you need both indices and values, use enumerate or index-based loops so the indices are always available.
First Match, All Matches, or a Count
The same loops can answer three kinds of question. What changes is what you do when a candidate passes the check.
- Existence or first match: return as soon as a candidate passes, like
two_sum_brute. - All matches: append every passing candidate to a list and return the list at the end.
- Count: increment a counter. Only correct loop bounds make the count correct.
def count_pairs_with_difference(nums, k):
count = 0
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if abs(nums[i] - nums[j]) == k:
count += 1
return count
def all_pairs_with_difference(nums, k):
pairs = []
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if abs(nums[i] - nums[j]) == k:
pairs.append((i, j))
return pairs
nums = [1, 5, 3, 4, 2]
print(count_pairs_with_difference(nums, 2)) # 3
print(all_pairs_with_difference(nums, 2)) # [(0, 2), (1, 2), (3, 4)]Suppose the inner loop were range(n) here. Every matching pair would be counted twice, once as (i, j) and once as (j, i), and the function would return 6. Some people "fix" that by dividing by 2 at the end. That patch hides the real mistake and fails as soon as k == 0, because then self-pairs add an extra count for every element. The better fix is to get the bounds right.
Breaking Out of Nested Loops
In Python, break exits only the innermost loop. When you want to stop the whole search at the first match, you have three options:
- Put the loops in a function and
return. This is the cleanest option and the onetwo_sum_bruteuses. - Set a flag and check it in the outer loop.
- Use
for ... else, which is compact but harder for many readers to follow.
def first_duplicate_pair(words):
found = None
for i in range(len(words)):
for j in range(i + 1, len(words)):
if words[i] == words[j]:
found = (i, j)
break # leaves only the inner loop
if found is not None:
break # leaves the outer loop too
return found
print(first_duplicate_pair(["a", "b", "c", "b", "a"])) # (0, 4)Pairs Across Two Collections
Sometimes the two items come from different lists: a shirt and a pair of trousers, a buyer and a seller. Pairs across two lists have no symmetry to exploit, so both loops run over their full ranges:
def count_cheaper_pairs(prices_a, prices_b):
"""Count pairs (a, b) with a from prices_a, b from prices_b, and a < b."""
count = 0
for a in prices_a:
for b in prices_b:
if a < b:
count += 1
return count
print(count_cheaper_pairs([1, 4, 6], [2, 5])) # 3: (1,2), (1,5), (4,5)The candidate count is len(prices_a) * len(prices_b). Starting the inner loop at i + 1 here would be a bug, because it would silently drop valid pairs.
Triples and Beyond
To search triples, add a third loop and keep the same rule: each loop starts one past the loop outside it. The result is strictly increasing indices i < j < k, so each unordered triple appears exactly once.
def three_sum_brute(nums, target):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if nums[i] + nums[j] + nums[k] == target:
return (i, j, k)
return None
print(three_sum_brute([4, 1, 7, 3, 9], 14)) # (0, 1, 4)
print(three_sum_brute([1, 2], 3)) # NoneThis visits n(n−1)(n−2)/6 triples. That is the binomial coefficient C(n, 3), which grows as O(n³). A later chapter checks whether costs like this fit the input limits. For now, notice that every extra loop multiplies the work by roughly n.
When k is a parameter
You cannot write a variable number of nested loops by hand. When the tuple size k is part of the input, use itertools. Each function in the module matches one of the shapes from the table:
| Shape | `itertools` call | Count for n = 4, k = 2 |
|---|---|---|
| Ordered, self allowed | `product(range(n), repeat=k)` | 16 |
| Ordered, distinct | `permutations(range(n), k)` | 12 |
| Unordered, distinct | `combinations(range(n), k)` | 6 |
| Unordered, self allowed | `combinations_with_replacement(range(n), k)` | 10 |
from itertools import combinations
def k_sum_brute(nums, k, target):
for idx in combinations(range(len(nums)), k):
if sum(nums[i] for i in idx) == target:
return idx
return None
print(k_sum_brute([4, 1, 7, 3, 9], 3, 14)) # (0, 1, 4)
print(k_sum_brute([4, 1, 7, 3, 9], 2, 10)) # (2, 3)
print(k_sum_brute([4, 1, 7, 3, 9], 6, 0)) # None: no 6-element tuples existcombinations yields index tuples in the same lexicographic order as hand-written i < j < k loops, so k_sum_brute(nums, 3, target) returns the same answer as three_sum_brute. Pass range(len(nums)) rather than nums itself whenever you need indices or the list may contain duplicates.
Common Errors Checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| An element pairs with itself | Inner loop starts at 0 or `i` | Start at `i + 1` for distinct pairs |
| Counts are exactly double | Ordered loops used for an unordered question | Use `j > i`; do not divide by 2 |
| Last element never checked | `range(n - 1)` used on the inner loop | The outer loop may stop at `n - 1`, the inner loop must reach `n` |
| `IndexError` | Loop over `range(n + 1)` or `nums[j + 1]` inside the loop | Recheck bounds against the indices you actually access |
| Wrong answer with duplicates | Looping over values instead of indices | Loop over indices or use `enumerate` |
| Search continues after a match | `break` only exits the inner loop | Return from a function or use a flag |
| Items skipped unpredictably | The list is modified while you loop over it | Build results in a separate list |
Exercise
You must count how many pairs of indices (i, j) with i < j satisfy nums[i] == nums[j]. A colleague writes two loops that both run over range(n), counts matches, and returns count // 2. For nums = [7, 7, 7], what does their code return, what is the correct answer, and how should the loops be written?
Show answer
Both loops over range(n) also match each index with itself, so they find 3 self-matches plus 6 ordered pairs, a total of 9. Their code returns 9 // 2 = 4. The correct answer is 3: (0,1), (0,2), and (1,2). Write the inner loop as range(i + 1, n) and return the count without dividing.
Exercise
Write a function closestpairgap(nums) that returns the smallest absolute difference between any two distinct elements of the list, or None if the list has fewer than two elements. Which loop shape do you need, and how many candidates does it check for n = 5?
Show answer
Use the unordered, distinct shape. For example: best = None; for i in range(len(nums)): for j in range(i + 1, len(nums)): d = abs(nums[i] - nums[j]); if best is None or d < best: best = d; then return best. Lists of length 0 or 1 never enter the inner loop, so the function returns None for them. For n = 5 it checks 5·4/2 = 10 pairs.
Exercise
A problem asks whether some ordered triple (a, b, c) of elements, where repeats of the same element are allowed, satisfies a*b == c. Which itertools call enumerates exactly this search space over indices, and how many candidates does it produce for n = 10?
Show answer
Order matters, because a*b == c treats c differently from a and b, and repeats are allowed. Use product(range(n), repeat=3). It produces 10^3 = 1000 candidates.