LeetCode Blind 75 in Swift: Solving the "3Sum" Problem

Problem: 3Sum

The 3Sum problem asks you to find all unique triplets in the array that give the sum of zero. Each triplet should be listed only once, even if multiple combinations can produce the same triplet.

Example:

Input: nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
Explanation: The two triplets with sum zero are [-1, -1, 2] and [-1, 0, 1].
        

Swift Solution

class Solution {
    func threeSum(_ nums: [Int]) -> [[Int]] {
        let nums = nums.sorted()
        var result = [[Int]]()

        for i in 0.. 0 && nums[i] == nums[i - 1] {
                continue
            }
            var left = i + 1
            var right = nums.count - 1

            while left < right {
                let sum = nums[i] + nums[left] + nums[right]
                if sum == 0 {
                    result.append([nums[i], nums[left], nums[right]])
                    left += 1
                    right -= 1
                    while left < right && nums[left] == nums[left - 1] {
                        left += 1
                    }
                    while left < right && nums[right] == nums[right + 1] {
                        right -= 1
                    }
                } else if sum < 0 {
                    left += 1
                } else {
                    right -= 1
                }
            }
        }
        
        return result
    }
}

let solution = Solution()
let nums = [-1, 0, 1, 2, -1, -4]
let result = solution.threeSum(nums)
print(result) // Output: [[-1, -1, 2], [-1, 0, 1]]
        

Explanation

In this solution, the array is first sorted, which helps in efficiently finding triplets that sum to zero. For each element, we use the two-pointer technique to find pairs that together with the current element sum to zero. Duplicates are skipped to ensure unique triplets.

Comments

Popular posts from this blog

LeetCode Blind 75 in Swift: Solving the "Find Minimum in Rotated Sorted Array" Problem

LeetCode Blind 75 in Swift: Solving the "Product of Array Except Self" Problem