Skip to content

Commit dbb43fc

Browse files
committed
add solution: 3sum
1 parent 64aa6d9 commit dbb43fc

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

3sum/dusunax.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'''
2+
# Leetcode 15. 3Sum
3+
4+
use **two pointers** to solve this problem.
5+
6+
## Time and Space Complexity
7+
8+
```
9+
TC: O(n^2)
10+
SC: O(1)
11+
```
12+
13+
### TC is O(n^2):
14+
- sorting the list = O(n log n)
15+
- iterating through the list and using two pointers to find the sum of three numbers. = O(n^2)
16+
17+
### SC is O(1):
18+
- sorting in place = O(1)
19+
'''
20+
21+
class Solution:
22+
def threeSum(self, nums: List[int]) -> List[List[int]]:
23+
nums.sort() # TC: O(n log n), SC: O(1)
24+
result = [] # result are part of the output => do not count toward auxiliary (extra) space.
25+
26+
for i in range(len(nums)): # TC: O(n^2)
27+
if i > 0 and nums[i] == nums[i - 1]:
28+
continue
29+
30+
j = i + 1
31+
k = len(nums) - 1
32+
while j < k:
33+
currSum = nums[i] + nums[j] + nums[k]
34+
35+
if currSum < 0:
36+
j += 1
37+
elif currSum > 0:
38+
k -= 1
39+
else:
40+
result.append([nums[i], nums[j], nums[k]])
41+
42+
while j < k and nums[j] == nums[j + 1]:
43+
j += 1
44+
while j < k and nums[k] == nums[k - 1]:
45+
k -= 1
46+
47+
j += 1
48+
k -= 1
49+
50+
return result

0 commit comments

Comments
 (0)