Sub topic 3
Pairs and Tuples with Nested Loops
This chapter assumes you can write Python functions and loops, index into lists, and read basic Big-O notation. Earlier chapters covered how to define a search space. Here you turn that definition into code: when the candidates are pairs or triples of elements, the search space becomes nested loops.
The Shape of a Pair Search
Many problems ask about two elements at once. You might need two numbers that sum to a target, two points that are closest together, or two intervals that overlap. The candidates are pairs of indices (i, j). A brute-force solution visits each candidate once and tests it.
The main decision is which pairs count as distinct candidates. Three loop shapes cover almost every case:
| Candidates wanted | Loop shape | Number of candidates |
|---|---|---|
| Unordered pairs, distinct indices | `j` from `i + 1` | n(n − 1) / 2 |
| Ordered pairs, distinct indices | `j` over all, skip `j == i` | n(n − 1) |
| Ordered pairs, repeats allowed | `j` over all | n² |
Pick the shape from the problem statement. If (i, j) and (j, i) give the same answer, as with sums, use the first shape. If order matters, as with "buy on day i, sell on day j", you usually still want j > i, and the problem's own constraint chooses the shape for you.
Two-Sum by Exhaustion
The two-sum problem asks for two different indices whose values add up to target. Because addition is symmetric, unordered pairs are enough:
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([3, 8, 1, 5], 9)) # (1, 2)
print(two_sum_brute([3, 8, 1, 5], 100)) # NoneStarting j at i + 1 does two jobs at once. It skips i == j, so no element pairs with itself, and it visits each unordered pair exactly once.
Extending to Triples and k-Tuples
For triples, add a third loop that starts after the second. The same start after the previous index rule gives each combination once:
def three_sum_count(nums, target):
n = len(nums)
count = 0
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:
count += 1
return count
print(three_sum_count([1, 2, 3, 4, 5], 9)) # 2: (1,3,5) and (2,3,4)When the tuple size k is fixed and small, write the loops out by hand. If k is a variable, hand-written loops stop working, and itertools.combinations(range(n), k) produces the same index tuples in the same order.
Common Errors
- Self-pairing. Writing
for j in range(len(nums))letsi == j, so[4]with target 8 wrongly returns(0, 0). - Double counting. When you count pairs instead of finding one, a full inner loop counts every pair twice.
- Wrong start index. Starting the inner loop at
iinstead ofi + 1brings back self-pairs. Starting ati + 2silently drops adjacent pairs. - Early return when you need all results. Returning the first match is fine for "find a pair" but wrong for "count" or "find the best".
- Mutating the list inside the loops. Removing elements shifts indices, and the loops then skip candidates.
Exercise
An inversion is a pair of indices i < j with nums[i] > nums[j]. Write a brute-force function count_inversions(nums) and state what it returns for [3, 1, 2].
Show answer
Use unordered pairs with j starting at i + 1, and count instead of returning early: count = 0; for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] > nums[j]: count += 1; then return count. For [3, 1, 2] it returns 2, from the pairs (3, 1) and (3, 2).
Exercise
A student writes the two-sum inner loop as for j in range(len(nums)) and adds no other check. Give an input where this returns a wrong answer, and say what it returns.
Show answer
nums = [5], target = 10. The pair (0, 0) is tested, and 5 + 5 == 10, so the function returns (0, 0) even though no two distinct indices exist. The correct answer is None.