Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 10ad1b5

Browse files
authored
Create 3Sum.py
1 parent 60dffde commit 10ad1b5

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

3Sum.py

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

0 commit comments

Comments
 (0)