15. 3Sum(Solution || Leetcode medium || Java)

Palakkgoyal
2 min readNov 17, 2022

--

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 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
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 are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.

Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.

Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.

Constraints:

  • 3 <= nums.length <= 3000
  • -105 <= nums[i] <= 105

SOLUTION:

class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//First sort the array, as without sorting it would become
// very typical to solve given question
Arrays.sort(nums);

//Create a list of list to store arrays and return them
List<List<Integer>> output = new ArrayList<List<Integer>>();

//Start looping through each number
for(int i = 0; i < nums.length - 2; i++){

//This condition will help us to skip duplicates
// after every loop
if(i == 0 || (i > 0 && nums[i] != nums[i-1])){
int low = i + 1;
int high = nums.length - 1;

//We will search for the combo that will result in
// zero if we add that combo to our nums[i]
int sum = -nums[i];


while(low < high){
//if found that combo add that in our arraylist
if(nums[low] + nums[high] == sum){
output.add(Arrays.asList(nums[i],nums[low],nums[high]));

//this condition is for skipping duplicates
while(low < high - 1 && nums[low] == nums[low + 1]) low++;
while(high > low + 1 && nums[high] == nums[high - 1]) high--;

low++;
high--;
}
else if(nums[low] + nums[high] > sum){
high--;
}
else{
low++;
}
}
}
}


return output;
}
}

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet