Thursday, August 13, 2015

all pairs in array that sum to k

//example:
k = 5
a    :  1  3  4  5  6  7  2  2 -1
delta:  4  2  1  0 -1 -2  3  3  6 // delta = k - a[i]
pairs: (1,4), (3,2), (3,2), (6,-1)

k = 5
a:     3 3 2 3
delta: 2 2 3 2
pairs: (3,2), (3,2), (2,3)
// O(n) time, O(n) space
(a, k):
    pairs = new
    map ncountmap = new
    for i = 0, i < a.length(), i++:
        n = a[i]
        delta = k - n
        dcount
        ncountmap.trygetvalue(delta, out dcount)
        for c = 0, c < dcount, c++:
            pairs.add({delta, n})
        ncount
        ncountmap.trygetvalue(n, out ncount)
        ncountmap[n] = ncount + 1
    return pairs
To get unique pairs (left unique or left-right unique):
k = 6
a    :  2  4  4  3  3  3
delta:  4  2  2  3  3  3
To get left unique pairs as (4,2), (2,4), (3,3):
// unique pairs (left): only one (4,2), (2,4), (3,3)
(n, k):
    if a == null:
        throw
    set nset = new
    set firstOfPair = new
    for n in a:
        delta = k - n
        if nset.has(delta):
            if !firstOfPair.has(delta):
                firstOfPair.add(delta)
                pairs.add({delta, n})
        if !nset.has(n):
            nset.add(n)
    return pairs
To get left-right unique pairs as (2,4), (3,3):
// unique pairs (left, right): only one (2,4), (3,3)
(n, k):
    if a == null:
        throw
    set nset = new
    set maxOfPair = new
    for n in a:
        delta = k - n
        if nset.has(delta):
            max = max(delta, n)
            if !maxOfPair.has(max):
                maxOfPair.add(max)
                pairs.add({delta, n})
        if !nset.has(n):
            nset.add(n)
    return pairs

No comments:

Post a Comment