Skip to content

16.24. Pairs With Sum

Description

Design an algorithm to find all pairs of integers within an array which sum to a specified value.

Example 1:


Input: nums = [5,6,5], target = 11

Output: [[5,6]]

Example 2:


Input: nums = [5,6,5,6], target = 11

Output: [[5,6],[5,6]]

Note:

  • nums.length <= 100000

Solutions

Solution 1: Hash Table

We can use a hash table to store the elements in the array, with the keys being the elements in the array and the values being the number of times the element appears.

We traverse the array, and for each element $x$, we calculate $y = target - x$. If $y$ exists in the hash table, it means that there is a pair of numbers $(x, y)$ that add up to the target, and we add it to the answer and reduce the count of $y$ by $1$. If $y$ does not exist in the hash table, it means that there is no such pair of numbers, and we increase the count of $x$ by $1$.

After the traversal, we can obtain the answer.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def pairSums(self, nums: List[int], target: int) -> List[List[int]]:
        cnt = Counter()
        ans = []
        for x in nums:
            y = target - x
            if cnt[y]:
                cnt[y] -= 1
                ans.