File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments