[LeetCode/Python] 15. 3Sum

도니·2025년 9월 28일

Interview-Prep

목록 보기
23/29
post-thumbnail

📌 Problem

[LeetCode] 15. 3Sum

📌 Solution

Idea

  • Fix the first pointer i and move the other two l, r with a while loop to find valid triplets
  • Continue searching by shifting l right and r left even after finding a sum of zero, since there may be other number combinations that also add up to zero
  • Skip repeated values of i, l, and r to avoid duplicate triplets

Code

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        nums.sort()
        res = []

        for i in range(n-2):
            # Skip duplicate i values
            if i > 0 and nums[i] == nums[i-1]:
                continue

            l, r = i+1, n-1
            while l < r:
                total = nums[i] + nums[l] + nums[r]
                
                if total == 0:
                    res.append([nums[i], nums[l], nums[r]])

                    # Skip duplicate l, r values
                    l += 1
                    while l < r and nums[l] == nums[l-1]:
                        l += 1
                    r -= 1
                    while l < r and nums[r] == nums[r+1]:
                        r -= 1
                elif total < 0:
                    l += 1
                else:
                    r -= 1

        return res
profile
Where there's a will, there's a way

0개의 댓글