Print Pairs with Given Sum

Problem Given an array of integers and a target sum, print all pairs of elements that add up to the target.

Input / Output

  • Input: array arr of n integers, and an integer target.
  • Output: every pair of elements summing to target. Clarify whether (2,3) and (3,2) count once or twice, and whether duplicate value-pairs should be printed once or once per occurrence.

Constraints

  • The array may contain duplicates and negative values.
  • Pairs are normally reported without repetition of ordering — (2,3) and (3,2) are the same pair.
  • An element cannot pair with itself at the same index, though two equal values at different indices are a valid pair.
  • Target O(n) time.

Example

  • arr = [1,5,7,-1,5], target = 6 -> (1,5), (7,-1), and (1,5) again from the second 5 if per-occurrence reporting is wanted; just (1,5) and (7,-1) for unique value-pairs.
  • arr = [3,3], target = 6 -> (3,3) is valid: two distinct indices holding the same value.
  • The [1,5,7,-1,5] case is exactly where the requirements must be pinned down before coding — the two answers differ and both are defensible.
asked …
LeaderboardSalaryAccount