""" Time: O(N^2) Space: O(1) First of all, we need to sort the list, so that it is easier to know where to move the pointers. (Keep in mind that sorting takes O(NLogN) of time, but since judging from the problem this solution might takes at least O(N^2), so it is ok to sort.) Now, we have 3 unique pointers at the list. i, j, k, where i List[List[int]]: ans = [] nums.sort() for i in range(len(nums)): if 00: break #[1] j, k = i+1, len(nums)-1 while j0: k -= 1 elif nums[i]+nums[j]+nums[k]<0: j += 1 else: ans.append((nums[i], nums[j], nums[k])) while 0 List[List[int]]: ans = set() seen = set() N = len(nums) for i, v1 in enumerate(nums): if v1 in seen: continue seen.add(v1) needed = set() for j, v2 in enumerate(nums[i+1:]): if v2 in needed: ans.add(tuple(sorted((v1, v2, -v1-v2)))) needed.add(-v1-v2) return ans class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: ans = [] nums.sort() for i in range(len(nums)): if nums[i]>0: break if i>0 and nums[i]==nums[i-1]: continue j = i+1 k = len(nums)-1 while j0: k -= 1 elif nums[j]+nums[k]+nums[i]<0: j += 1 else: ans.append((nums[i], nums[j], nums[k])) while j