easyArraysPattern: Two Pointers

Pair Sum Problem Solution

Problem Statement

Given an array of integers, find all pairs of integers that sum up to a target value.

Examples

Example 1:
Input:[1, 2, 3, 4, 5] 7
Output:[2, 5], [3, 4]
Example 2:
Input:[1, 2, 3, 4, 5] 8
Output:[]
Example 3:
Input:[2, 5, 8, 12]
Output:[2, 6], [3, 5], [4, 4], [5, 3], [8, 4], [12, 2]

Constraints

  • 1 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • 1 <= target <= 2000
Time: O(n) Space: O(n)
Use a hash map to store the frequency of each number, then iterate over the array to find pairs that sum up to the target.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

def pairSumProblem(nums, target): freq = {} pairs = [] for num in nums: freq[num] = freq.get(num, 0) + 1 for num1 in freq: num2 = target - num1 if num2 == num1 or num2 not in freq: continue pairs.append([num1, num2]) return pairs