LeetCode 15 - Three Sum Problem

Problem Statement

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.


The solution set must not contain duplicate triplets.


Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
  [-1, 0, 1],
  [-1, -1, 2]


class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() output = [] for i in range(len(nums)-2): if i==0 or (i>0 and nums[i]!=nums[i-1]): low=i+1 high = len(nums)-1 target = 0-nums[i] while low<high: if nums[low]+nums[high] == target: output.append([nums[i], nums[low], nums[high]]) while low<high and nums[low]==nums[low+1]: low+=1 while low>high and nums[high]==nums[high-1]: high-=1 low+=1 high-=1 elif nums[low]+nums[high]>target: high-=1 else: low+=1 return output