Skip to content

https://leetcode.com/problems/3sum/editorial/

python
from collections import Counter

class Solution:
    def threeSum(self, A: List[int]) -> List[List[int]]:
        if not A:
            return []
        N=len(A)
        D={}
        S=set()

        A.sort()
        k=1
        B=[A[0]]
        for i in range(1,N):
            if A[i]==A[i-1]:
                k+=1
            else:
                k=1
            if k<=2 or k<=3 and A[i]==0:
                B.append(A[i])
        A=B
        N=len(A)
        for i,a in enumerate(A):
            D[a]=i
        
        for i in range(N):
            for j in range(i+1,N):
                C=-(A[i]+A[j]) # complement
                if C in D and D[C]!=i and D[C]!=j:
                    S.add(tuple(sorted([A[i],A[j],C])))
        ret=[]
        for l in S:
            ret.append(l)
        return ret