Leet Code

#9 13 3Sum

brian | Published: Jan. 25, 2025, 7:32 p.m. | Updated: May 25, 2025, 3:51 p.m.

Profile Picture
'''
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such 
that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.
'''

class Solution(object):
    def threeSum(self, nums:list[int]):
        res = []
        nums.sort()
        print(nums)
     

        for i, number in enumerate(nums):
            forCounter = 0
            #if index is not the first (0) &
            #the value is not the same as the previous value (we dont want duplicate)
            if i > 0 and number == nums[i - 1]:
                continue
            #left pointer val will always be 1 ahead of the current index
            leftPointer = i + 1
            rightPointer = len(nums) - 1 #right pointer begins at the end

            #so they wont cross
            while leftPointer < rightPointer:
                answer = number + nums[leftPointer] + nums[rightPointer]
                if answer > 0:
                    rightPointer-=1
                elif answer < 0:
                    leftPointer+=1
                else:
                    forCounter+=1
                    print(forCounter)
                    res.append([number, nums[leftPointer], nums[rightPointer]])
                    leftPointer+=1
                    rightPointer-= 1
                    
                    #if its the same value as the previous, then update again the left pointer
                    while nums[leftPointer] == nums[leftPointer - 1] and leftPointer < rightPointer:
                        leftPointer+=1
        return res

if __name__ == '__main__':
    nums = [-1, 0, 1, 2, -1, -4]
    obj1 = Solution()

    print(obj1.threeSum(nums))