-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path3Sum.py
63 lines (55 loc) · 2.39 KB
/
3Sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# Solution - 1 | O(N**2) Time and O(N) Space
class Solution:
def threeSum(self, nums):
nums.sort()
result = []
for left in range(len(nums) - 2): # renamed this to left because this will always be the leftmost pointer in the triplet
if left > 0 and nums[left] == nums[left - 1]: # this step makes sure that we do not have any duplicates in our result output
continue
mid = left + 1 # renamed this to mid because this is the pointer that is between the left and right pointers
right = len(nums) - 1
while mid < right:
curr_sum = nums[left] + nums[mid] + nums[right]
if curr_sum < 0:
mid += 1
elif curr_sum > 0:
right -= 1
else:
result.append([nums[left], nums[mid], nums[right]])
while mid < right and nums[mid] == nums[mid + 1]: # Another conditional for not calculating duplicates
mid += 1
while mid < right and nums[right] == nums[right - 1]: # Avoiding duplicates check
right -= 1
mid += 1
right -= 1
return result
# Solution - 2 | O(N**2) Time and O(N) Space
from collections import Counter
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
visited = set()
ans, n = set(), len(nums)
def two_sum(arr, target):
c = Counter(arr)
res = set()
for i in arr:
x = target - i
if x in c:
if x == i and c[x] > 1:
if (i,x) not in res and (x,i) not in res:
res.add((i, x))
elif x != i:
if (i,x) not in res and (x,i) not in res:
res.add((i, x))
return res
for i,v in enumerate(nums):
if v not in visited:
t_arr = nums[:i] + nums[i+1:]
ts = two_sum(t_arr, -v)
if ts:
for item in ts:
t = [v] + list(item)
t.sort()
ans.add(tuple(t))
visited.add(v)
return ans