math
problem-solving
number theory
combinatorics
pairs-sum

Find two pairs of pairs that sum to the same value

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The task is to find two distinct pairs of elements whose sums are equal. In algorithm terms, you want indices (i, j) and (k, l) such that a[i] + a[j] == a[k] + a[l], while also making sure the two pairs do not reuse the same array positions.

A Hash Map of Pair Sums Is the Standard Solution

The direct way to solve the problem is to examine every pair once, compute its sum, and remember the first pair seen for each sum. When another pair produces the same sum, compare indices. If the indices are disjoint, you found a valid answer.

python
1def find_equal_sum_pairs(values):
2    seen = {}
3
4    for i in range(len(values)):
5        for j in range(i + 1, len(values)):
6            pair_sum = values[i] + values[j]
7
8            if pair_sum in seen:
9                x, y = seen[pair_sum]
10                if len({i, j, x, y}) == 4:
11                    return (x, y), (i, j)
12            else:
13                seen[pair_sum] = (i, j)
14
15    return None
16
17
18items = [3, 4, 7, 1, 2, 9, 8]
19print(find_equal_sum_pairs(items))

A possible result is ((0, 6), (2, 4)), because 3 + 8 equals 7 + 2.

Why This Works

For every possible sum, the only information you need at first is one previously seen pair. When a second pair creates the same sum, you compare the four indices. If none overlap, the problem is solved. If they do overlap, you keep scanning.

The runtime is O(n^2) because there are n * (n - 1) / 2 pairs. That is unavoidable in the general case because the answer depends on relationships between pairs, not individual values.

Return Values Instead of Indices if You Prefer

Sometimes the problem asks for the values themselves rather than positions. You can map the returned indices back to the array.

python
1def equal_sum_pair_values(values):
2    answer = find_equal_sum_pairs(values)
3    if answer is None:
4        return None
5
6    (i, j), (k, l) = answer
7    return (values[i], values[j]), (values[k], values[l])
8
9
10print(equal_sum_pair_values([3, 4, 7, 1, 2, 9, 8]))

Output:

text
((3, 8), (7, 2))

Whether you return indices or values depends on whether duplicates matter. Indices are usually safer because they prove the pairs are distinct even when values repeat.

Handling Multiple Answers

Some inputs contain many valid pairs for the same sum. If you need all solutions rather than the first one, store a list of prior pairs for each sum instead of only one pair.

python
1def all_equal_sum_pairs(values):
2    seen = {}
3    results = []
4
5    for i in range(len(values)):
6        for j in range(i + 1, len(values)):
7            pair_sum = values[i] + values[j]
8            for x, y in seen.get(pair_sum, []):
9                if len({i, j, x, y}) == 4:
10                    results.append(((x, y), (i, j)))
11            seen.setdefault(pair_sum, []).append((i, j))
12
13    return results

That increases memory use, but it is the right tradeoff if completeness matters.

Sorting Is Possible but Usually Less Natural

You could sort pair sums and then look for adjacent equal values, but that still requires generating all pairs first. In practice, the hash-map version is simpler and often faster to implement correctly.

The main thing to preserve is the non-overlapping-index rule. Many buggy solutions detect equal sums but accidentally reuse one element in both pairs.

Common Pitfalls

  • Checking pair sums without verifying that the two pairs use four distinct indices.
  • Returning values instead of indices in a way that hides duplicate-position reuse.
  • Assuming the first repeated sum always gives a valid answer without overlap checks.
  • Storing every pair unnecessarily when only one pair per sum is needed for the first-match problem.
  • Forgetting that the general solution is naturally O(n^2) because all pairs must be considered.

Summary

  • Use a hash map from pair sum to previously seen pair indices.
  • When the same sum appears again, verify that the two pairs do not share indices.
  • Returning indices is safer than returning values when duplicates exist.
  • Store all pairs per sum only if the problem asks for every solution.
  • 'O(n^2) time is expected because the problem is defined over element pairs.'

Course illustration
Course illustration

All Rights Reserved.