Problem Description
The problem 3Sum is given an integer array nums
, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
Example:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Solution
To solve the problem, we follow the steps below:
We sort the array using
nums.sort()
.We iterate over each element in the array using a
for
loop.Inside the loop, we check if the current element is a positive integer or not. If it is, we break out of the loop.
If the current element is not a positive integer, we check if it is a duplicate of the previous element. If it is, we skip it using the
continue
statement. If it is not, we initialize two variablesl
andr
.l
will point to the next element after the current element, andr
will point to the last element in the array.We then use a
while
loop which will continue untill
is less thanr
. Inside thewhile
loop, we calculate the sum of the current element,lth
element, andrth
element. If the sum is greater than 0, we decrementr
usingr -= 1
. If it is less than 0, we incrementl
usingl += 1
. If it is equal to 0, we append the triplet to the result and incrementl
and decrementr
usingl += 1
andr -= 1
. We then check if the next element afterl
is a duplicate of the current element. If it is, we skip it using thewhile
loop.Finally, we return the result using
return res
.
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for i, a in enumerate(nums):
# Skip positive integers
if a > 0:
break
if i > 0 and a == nums[i - 1]:
continue
l, r = i + 1, len(nums) - 1
while l < r:
threeSum = a + nums[l] + nums[r]
if threeSum > 0:
r -= 1
elif threeSum < 0:
l += 1
else:
res.append([a, nums[l], nums[r]])
l += 1
r -= 1
while nums[l] == nums[l - 1] and l < r:
l += 1
return res
Complexity Analysis
The time complexity of this algorithm is O(n^2)
. This is because we are using nested loops to iterate over the array. The space complexity of this algorithm is O(1)
, since we are not using any extra space.
Conclusion
In this blog post, we have solved the LeetCode problem "3Sum" using Python. We have explained the solution step-by-step and provided a complexity analysis. Happy Coding!😎