3Sum medium
Problem Statement
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.
Example 1
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: Because there are two triplets whose sum is 0: (-1) + (-1) + 2 = 0 (-1) + 0 + 1 = 0
Example 2
Input: nums = [0,1,1] Output: [] Explanation: There are no triplets whose sum is 0
Steps
-
Sort the array: Sorting allows us to easily skip duplicate numbers and optimize the search for triplets.
-
Iterate through the array: The outer loop iterates through each number
nums[i]
as a potential first element of a triplet. -
Two-pointer approach: For each
nums[i]
, we use two pointers,left
andright
, to search for the remaining two numbers that sum to-nums[i]
.left
starts ati + 1
andright
starts at the end of the array. -
Sum and adjust pointers: We calculate the sum
sum = nums[i] + nums[left] + nums[right]
.- If
sum
is 0, we've found a triplet. Add it to the result set, but make sure to skip duplicate numbers by incrementingleft
and decrementingright
until we encounter unique numbers. - If
sum
is less than 0, it means we need a larger sum, so we incrementleft
. - If
sum
is greater than 0, it means we need a smaller sum, so we decrementright
.
- If
-
Skip duplicates: After finding a triplet, we increment
left
and decrementright
while they point to duplicate numbers to avoid adding duplicate triplets to the result.
Explanation
The algorithm uses a combination of sorting and a two-pointer technique to efficiently find all unique triplets that sum to zero. Sorting enables easy duplicate handling and efficient searching using the two pointers. The two-pointer approach allows for a linear time complexity within the nested loop, resulting in an overall time complexity of O(n^2).
Code
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public IList<IList<int>> ThreeSum(int[] nums) {
Array.Sort(nums); // Sort the array
IList<IList<int>> result = new List<IList<int>>();
for (int i = 0; i < nums.Length - 2; i++) {
// Skip duplicate numbers for the first element
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = nums.Length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.Add(new List<int> { nums[i], nums[left], nums[right] });
// Skip duplicate numbers for the second and third elements
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
}
Complexity
- Time Complexity: O(n^2), where n is the length of the input array. The sorting takes O(n log n), but the nested loops dominate the time complexity.
- Space Complexity: O(log n) in the best case (due to the space used by the sorting algorithm, which can be in-place for some implementations), or O(n) in the worst case for certain sorting algorithms, and O(m) where m is the number of triplets found. The space used by the
result
list depends on the number of triplets. In most scenarios,m
will be significantly smaller thann
.