Three Sum

Find all unique triplets in an array that sum to a target value.

Code

Algorithms
a = sorted(arr)
result = []
for i in range(len(a) - 2):
    if i > 0 and a[i] == a[i - 1]:
        continue
    l, r = i + 1, len(a) - 1
    while l < r:
        s = a[i] + a[l] + a[r]
        if s == target:
            result.append([a[i], a[l], a[r]])
            while l < r and a[l] == a[l + 1]: l += 1
            while l < r and a[r] == a[r - 1]: r -= 1
            l += 1; r -= 1
        elif s < target: l += 1
        else: r -= 1
result

Parameters

Array of numbers

Target sum

Server

More Python Snippets