Created
March 5, 2025 12:21
-
-
Save linminhtoo/5689ea9ae0672b7c6ccc1ac56c172e51 to your computer and use it in GitHub Desktop.
3 sum with 2 pointers without hashmap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
# two-pointer solution | |
def threeSum(self, nums: list[int]) -> list[int]: | |
nums.sort() | |
seen = set() | |
len_nums = len(nums) | |
result_triplets = [] | |
for i in range(len_nums): | |
num = nums[i] | |
# de-duplicate | |
if num in seen: | |
continue | |
seen.add(num) | |
left = i + 1 | |
right = len_nums - 1 | |
pairs_seen = set() | |
# since array is sorted, as long as we format our pairs as: (nums_left, nums_right) | |
# they will be sorted and unique | |
while left < right: | |
nums_left = nums[left] | |
nums_right = nums[right] | |
curr_sum = num + nums_left + nums_right | |
if curr_sum == 0: | |
if (nums_left, nums_right) in pairs_seen: | |
# i wonder if we could do right -= 1 instead? | |
# yes, it still works | |
left += 1 | |
continue | |
pairs_seen.add((nums_left, nums_right)) | |
result_triplets.append([num, nums_left, nums_right]) | |
elif curr_sum < 0: | |
# since `nums` is sorted, incrementing left helps us raise curr_sum towards 0 | |
left += 1 | |
continue | |
else: | |
# since `nums` is sorted, decrementing right helps us lower curr_sum towards 0 | |
right -= 1 | |
continue | |
return result_triplets |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment