File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import List
2+
3+ class Solution :
4+ def threeSum (self , nums : List [int ]) -> List [List [int ]]:
5+ result = []
6+ nums .sort () # sort nums before using two-pointers
7+
8+ for i , num in enumerate (nums ):
9+ # skip duplicated targets
10+ if i > 0 and nums [i ] == nums [i - 1 ]:
11+ continue
12+
13+ target = - num
14+ left , right = i + 1 , len (nums ) - 1
15+
16+ while left < right :
17+ if nums [left ] + nums [right ] == target :
18+ result .append ([num , nums [left ], nums [right ]])
19+
20+ # skip duplicated numbers ( ex. nums = [-3 0 0 0 3 3] )
21+ while left < right and nums [left ] == nums [left + 1 ]:
22+ left += 1
23+ while left < right and nums [right ] == nums [right - 1 ]:
24+ right -= 1
25+
26+ left += 1
27+ right -= 1
28+ elif nums [left ] + nums [right ] < target :
29+ left += 1
30+ else :
31+ right -= 1
32+
33+ return result
34+
35+
36+ # Time Complexity: O(n^2)
37+ # - Sorting takes O(n log n).
38+ # - The outer loop runs O(n) times, and the two-pointer approach inside runs O(n) for each iteration.
39+ # - Combined, the overall time complexity is O(n^2).
40+
41+ # Space Complexity: O(k)
42+ # - The result list uses O(k) space, where k is the number of unique triplets in the output.
You can’t perform that action at this time.
0 commit comments