Skip to content

Commit

Permalink
Adds medium two pointer exercise - triples - 3sum
Browse files Browse the repository at this point in the history
  • Loading branch information
joffilyfe committed Jan 17, 2024
1 parent ac7b4fc commit e8332fd
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions 15.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from typing import List
import unittest


class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
triplets = []
nums.sort()
size = len(nums)

for i in range(size - 1):
if i > 0 and nums[i] == nums[i - 1]:
continue

j = i + 1
z = size - 1

while j < z:
sum = nums[i] + nums[j] + nums[z]

if sum > 0:
z -= 1
elif sum < 0:
j += 1
else:
triplets.append([nums[i], nums[j], nums[z]])
j += 1
z -= 1

while nums[j] == nums[j - 1] and j < z:
j += 1

return triplets


class Tests(unittest.TestCase):
def test_one(self):
self.assertEqual(
Solution().threeSum(nums=[-1, 0, 1, 2, -1, -4]), [[-1, -1, 2], [-1, 0, 1]]
)

def test_two(self):
self.assertEqual(Solution().threeSum(nums=[0, 0, 1]), [])

def test_three(self):
self.assertEqual(Solution().threeSum(nums=[0, 0, 0]), [[0, 0, 0]])


if __name__ == "__main__":
unittest.main()

0 comments on commit e8332fd

Please sign in to comment.