Print Pairs with Given Sum
viaGlassdoor
Problem: Given an array of integers and a target sum, print all pairs of elements that add up to the target sum.
Constraints: Array may contain duplicates; pairs should typically be reported without repetition (e.g., (2,3) and (3,2) counted once).
Example: arr = [1,5,7,-1,5], target = 6 -> pairs: (1,5), (7,-1), (1,5) (if duplicates allowed).
Approach: Use a hash set - iterate through the array, and for each element x, check whether (target - x) exists in the set of elements seen so far; if so, output the pair, then add x to the set. O(n) time, O(n) space. (A sorted-array two-pointer approach also works in O(n log n) time, O(1) extra space if sorting in place is allowed.)
asked …