Brute Force
Intuition
The most direct approach is to check every possible combination of three elements. We use three nested loops to generate all triplets and check if they sum to zero. To avoid duplicates we can sort the array first and skip elements that are the same as the previous one at each loop level. While simple to understand, the cubic time complexity makes this approach too slow for large inputs.
Algorithm
- Sort the input array in ascending order.
- Use three nested loops to iterate through all combinations of indices i < j < k.
- For each combination, check if nums[i] + nums[j] + nums[k] equals 0.
- Skip duplicate values at each level to avoid duplicate triplets.
- If the sum is zero, add the triplet to the result list.
O(n^3)SpaceO(1) excluding the output arrayCode (C++ · Java · Python · Go)
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
int n = nums.size();
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n - 1; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
for (int k = j + 1; k < n; k++) {
if (k > j + 1 && nums[k] == nums[k - 1]) continue;
if (nums[i] + nums[j] + nums[k] == 0) {
result.push_back({nums[i], nums[j], nums[k]});
}
}
}
}
return result;
}
};class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n - 1; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
for (int k = j + 1; k < n; k++) {
if (k > j + 1 && nums[k] == nums[k - 1]) continue;
if (nums[i] + nums[j] + nums[k] == 0) {
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
}
}
}
}
return result;
}
}def threeSum(nums: list[int]) -> list[list[int]]:
result = []
nums.sort()
n = len(nums)
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 1):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
for k in range(j + 1, n):
if k > j + 1 and nums[k] == nums[k - 1]:
continue
if nums[i] + nums[j] + nums[k] == 0:
result.append([nums[i], nums[j], nums[k]])
return resultimport "sort"
func threeSum(nums []int) [][]int {
sort.Ints(nums)
var result [][]int
n := len(nums)
for i := 0; i < n-2; i++ {
if i > 0 && nums[i] == nums[i-1] {
continue
}
for j := i + 1; j < n-1; j++ {
if j > i+1 && nums[j] == nums[j-1] {
continue
}
for k := j + 1; k < n; k++ {
if k > j+1 && nums[k] == nums[k-1] {
continue
}
if nums[i]+nums[j]+nums[k] == 0 {
result = append(result, []int{nums[i], nums[j], nums[k]})
}
}
}
}
return result
}