Given an integer array, output all of the unique pairs that sum up to a specific value k.
Here is the standard solution, in O(n) time:
if len(arr) < 2:
return
seen = set()
output = set()
for num in arr:
target = k - num
if target not in seen:
seen.add(num)
else:
output.add((min(num, target), max(num, target)))
return print('\n'.join(map(str, list(output))))
I have a few questions regarding this solution:
1) Why do we use a set to store the seen values of the array? Why not a list? Does this change anything?
2) Why the min(num, target), max(num, target)? Is this for the sake of consistent formatting or is there a deeper reason behind this? At first, I thought it would be to deal with duplicate cases such as (1,3) & (3,1), but this solution doesn't come across that I don't think?