15. 3Sum ๐
Difficulty: Medium
- Tags: Array
, Two Pointers
, Sorting
Problem Statement ๐
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.
Examples ๐
๐น Example 1:
Input:
Output:
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0
.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0
.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0
.
The distinct triplets that sum up to 0 are [-1,0,1]
and [-1,-1,2]
. The order of the output and the order of the triplets does not matter.
๐น Example 2:
Input:
Output:
Explanation: The only possible triplet does not sum up to 0.
๐น Example 3:
Input:
Output:
Explanation: The only possible triplet sums up to 0.
Constraints โ๏ธ
3 <= nums.length <= 3000
-10^5 <= nums[i] <= 10^5
Solution ๐ก
To solve this problem, we can use the Two-Pointer Technique after sorting the array:
Sort the Array: This helps in easily skipping duplicates and using the two-pointer approach.
Iterate Through the Array: Use a loop to fix one element at a time and then use two pointers to find pairs that sum to the negative of the fixed element.
Two Pointers:
Set
left
pointer to the next element after the fixed element, andright
pointer to the end of the array.Calculate the sum of the three elements. If the sum is less than zero, increment the left pointer to increase the sum. If the sum is greater than zero, decrement the right pointer to decrease the sum.
If the sum is zero, record the triplet and skip duplicates for both the left and right pointers.
Skip Duplicates: After finding a triplet, increment
left
and decrementright
while skipping over any duplicate values.
Java Solution
Time Complexity โณ
O(n^2), where
n
is the length of the array. Sorting the array takesO(n log n)
and the two-pointer traversal takesO(n^2)
in the worst case.
Space Complexity ๐พ
O(1), as we are using a constant amount of extra space for pointers and indices. The space required for storing the output is not considered in the space complexity analysis.
You can find the full solution here.
Last updated