You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
5
+
Notice that the solution set must not contain duplicate triplets.
6
+
7
+
Example 1:
8
+
Input: nums = [-1,0,1,2,-1,-4]
9
+
Output: [[-1,-1,2],[-1,0,1]]
10
+
Example 2:
11
+
Input: nums = []
12
+
Output: []
13
+
Example 3:
14
+
Input: nums = [0]
15
+
Output: []
16
+
'''
17
+
18
+
# Brute Force
19
+
# Time Complexity: O(n^3)
20
+
# Space Complexity: O(m)
21
+
22
+
'''
23
+
In the brute force approach, we use three nested loops to iterate through all possible triplets in the array.
24
+
We check if the sum of each triplet is equal to zero and if it is, we add it to the result set.
25
+
The result set is used to avoid duplicates.
26
+
We convert the triplet to a tuple and add it to the set.
27
+
Finally, we convert the set back to a list of lists before returning it.
28
+
'''
29
+
30
+
classSolution:
31
+
defthreeSum(self, nums):
32
+
res=set()
33
+
foriinrange(len(nums)):
34
+
forjinrange(i+1,len(nums)):
35
+
forkinrange(j+1,len(nums)):
36
+
ifnums[i]+nums[j]+nums[k]==0:
37
+
res.add(tuple(sorted([nums[i],nums[j],nums[k]])))
38
+
39
+
return [list(triplet) fortripletinres]
40
+
41
+
# Two Pointers
42
+
# Time Complexity: O(n^2)
43
+
# Space Complexity: O(1) or O(n) depending on the sorting algorithm. O(m) for the result list.
44
+
45
+
'''
46
+
In the two pointers approach, we first sort the array.
47
+
Then we iterate through the array and for each element, we use two pointers to find the other two elements that sum to zero.
48
+
We set the left pointer to the next element and the right pointer to the last element.
49
+
We check if the sum of the three elements is equal to zero. If it is, we add it to the result list.
50
+
If the sum is greater than zero, we move the right pointer to the left. If the sum is less than zero, we move the left pointer to the right.
51
+
We also check for duplicates by skipping over elements that are the same as the previous element.
52
+
We continue this process until the left pointer is less than the right pointer.
0 commit comments