easyArraysPattern: Two Pointers

Find Pairs of Array Elements Summing to Target Solution

Problem Statement

You are given an array of integers and a target integer. Find all pairs of elements in the array that sum up to the target integer.

Examples

Example 1:
Input:[1, 2, 3, 4, 5]
Output:[]
Explanation: Pairs [1, 5] and [2, 4] add up to the target sum 6.
Example 2:
Input:[-1, 0, 1, 2, 3]
Output:[]
Explanation: Pairs [-1, 3] and [0, 2] add up to the target sum 2.
Example 3:
Input:[2, 2, 2, 2]
Output:[]
Explanation: All pairs [2, 2] add up to the target sum 4.

Constraints

  • The input array may be empty or contain duplicate elements.
  • The input array may contain negative numbers.
  • The target sum may be positive or negative.
Time: O(n) Space: O(n)
Use a hash table to store the elements you have seen so far, resulting in a time complexity of O(n) and a space complexity of O(n).

Run, Test & Submit Code

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

Solve on Interactive Workspace

Tested Solutions

def findPairsWithTargetSum(nums, targetSum) -> list: hashTable = {} pairs = [] for num in nums: complement = targetSum - num if complement in hashTable: pairs.append([complement, num]) hashTable[num] = 1 return pairs