Skip to main content
deleted 38 characters in body
Source Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237

I'm sorry for the late reply.

I came up with the following, which ends up using a dictionary as a helper to avoid the set operations and extra testing:

def sum_of_pairs_matches(K, arr):
    uniques = {i: True for i in arr}
    pairs = set()
    for val in arr:
        k = -val + K if val<K else -K - val
        if(uniques.get(k, False)):
            pairs.add(tuple(sorted([k,val])))
    return pairs

runningRunning:

sum_of_pairs_matches(5, [-5, -4, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

will yield

 {(-5, 10), (-4, 9), (-1, 6), (0, 5), (1, 4), (2, 3)}

I'm sorry for the late reply.

I came up with the following, which ends up using a dictionary as a helper to avoid the set operations and extra testing

def sum_of_pairs_matches(K, arr):
    uniques = {i: True for i in arr}
    pairs = set()
    for val in arr:
        k = -val + K if val<K else -K - val
        if(uniques.get(k, False)):
            pairs.add(tuple(sorted([k,val])))
    return pairs

running:

sum_of_pairs_matches(5, [-5, -4, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

will yield

 {(-5, 10), (-4, 9), (-1, 6), (0, 5), (1, 4), (2, 3)}

I came up with the following, which ends up using a dictionary as a helper to avoid the set operations and extra testing:

def sum_of_pairs_matches(K, arr):
    uniques = {i: True for i in arr}
    pairs = set()
    for val in arr:
        k = -val + K if val<K else -K - val
        if(uniques.get(k, False)):
            pairs.add(tuple(sorted([k,val])))
    return pairs

Running:

sum_of_pairs_matches(5, [-5, -4, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

will yield

{(-5, 10), (-4, 9), (-1, 6), (0, 5), (1, 4), (2, 3)}
Source Link

I'm sorry for the late reply.

I came up with the following, which ends up using a dictionary as a helper to avoid the set operations and extra testing

def sum_of_pairs_matches(K, arr):
    uniques = {i: True for i in arr}
    pairs = set()
    for val in arr:
        k = -val + K if val<K else -K - val
        if(uniques.get(k, False)):
            pairs.add(tuple(sorted([k,val])))
    return pairs

running:

sum_of_pairs_matches(5, [-5, -4, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

will yield

 {(-5, 10), (-4, 9), (-1, 6), (0, 5), (1, 4), (2, 3)}