Skip to content

Commit c30f79c

Browse files
authored
Create 3Sum.py
This program solves 3 Sum array problem in data structures
1 parent 0abeeab commit c30f79c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

data_structures/arrays/3Sum.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
def three_sum(nums):
2+
# Sort the array to simplify the problem
3+
nums.sort()
4+
result = []
5+
6+
# Iterate over the array
7+
for i in range(len(nums)):
8+
# Skip duplicates for the first element
9+
if i > 0 and nums[i] == nums[i - 1]:
10+
continue
11+
12+
# Two pointers approach
13+
left, right = i + 1, len(nums) - 1
14+
while left < right:
15+
total = nums[i] + nums[left] + nums[right]
16+
17+
if total == 0:
18+
# Found a valid triplet
19+
result.append([nums[i], nums[left], nums[right]])
20+
left += 1
21+
right -= 1
22+
23+
# Skip duplicates for the second and third elements
24+
while left < right and nums[left] == nums[left - 1]:
25+
left += 1
26+
while left < right and nums[right] == nums[right + 1]:
27+
right -= 1
28+
29+
elif total < 0:
30+
# Move the left pointer to increase the sum
31+
left += 1
32+
else:
33+
# Move the right pointer to decrease the sum
34+
right -= 1
35+
36+
return result

0 commit comments

Comments
 (0)