The problem is:
Given an integer array
nums
, return all the triplets[nums[i], nums[j], nums[k]]
wherei
,j
andk
are distinct andnums[i] + nums[j] + nums[k] == 0
.The solution set must not contain duplicate triplets and the order of the output and the order of the triplets does not matter.
This is my code:
def threeSum(nums):
triples = set() # this is where the triples will be stored
num_map = {}
n = len(nums)
for i in range(n): # creating a hash map of the array for quick lookups
num_map[nums[i]] = i
for i in range(n-1):
for j in range(i+1,n):
comp = - nums[i] - nums[j] # the complement
if (comp in num_map and num_map[comp] != i and num_map[comp] != j):
triples.add(tuple(sorted([nums[i],nums[j],comp])))
return triples
My questions are:
- I believe the time complexity of my solution is O(n^2), and it is not known if there is an algorithm which can perform better than O(n^2). Am I correct?
- In any event, it would seem that my code is not efficient. Which part of the code is slowing it down?
I suspected the use of sorted()
might be adding to it, but given that it is only sorting an array of 3 elements (and is only triggered if a solution is found), I thought it might not be having much impact. The reason I sort the array is to avoid duplicates.