This solution has Time Limit Exceeded error because it does not optimize for removing duplicates.

def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result_set = set() sorted_nums = sorted(nums) # print sorted_nums # i the outer index for i in range(len(sorted_nums)): # j, k are two inter index to sum j = 0; k = len(sorted_nums) - 1 target = 0 - sorted_nums[i] while j < k: if i == j: j += 1; continue elif i == k: k -= 1; continue s = sorted_nums[j] + sorted_nums[k] if s == target: # print i, j, k result_set.add( tuple( sorted([sorted_nums[i],sorted_nums[j],sorted_nums[k]]) ) ) if s > target: k -= 1 else: j += 1 results = [list(result) for result in sorted(result_set)] return resultsThis solution has optimization for removing duplications:

def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ results = [] nums.sort() for i in range(len(nums)-2): l = i + 1; r = len(nums) - 1 target = 0 - nums[i] if i == 0 or nums[i] != nums[i-1]: while l < r: s = nums[l] + nums[r] if s == target: results.append([nums[i], nums[l], nums[r]]) while l < r and nums[l] == nums[l+1]: l += 1 while l < r and nums[r] == nums[r-1]: r -= 1 l += 1; r -=1 elif s < target: l += 1 else: r -= 1 return results