Skip to content

Commit 863025e

Browse files
committed
solve 3sum
1 parent 1add9e6 commit 863025e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

3sum/samthekorean.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# O(n^2) where there is nested loop.
2+
# O(1) where high and low are reused as constant values.
3+
4+
5+
class Solution:
6+
def threeSum(self, nums: List[int]) -> List[List[int]]:
7+
# Initialize a set to store unique triplets
8+
triplets = set()
9+
10+
# Sort the list to make two-pointer approach possible
11+
nums.sort()
12+
13+
# Iterate through the list, considering each element as a potential first element of a triplet
14+
for i in range(len(nums) - 2):
15+
low = i + 1
16+
high = len(nums) - 1
17+
18+
# To avoid duplicate iteration
19+
while low < high:
20+
three_sum = nums[i] + nums[low] + nums[high]
21+
22+
if three_sum < 0:
23+
low += 1
24+
elif three_sum > 0:
25+
high -= 1
26+
else:
27+
triplets.add((nums[i], nums[low], nums[high]))
28+
low += 1
29+
high -= 1

0 commit comments

Comments
 (0)