Skip to content

Instantly share code, notes, and snippets.

@SahilKadam
Created March 9, 2017 06:20
Show Gist options
  • Save SahilKadam/aea269f11edc6a259130cdd4e731a332 to your computer and use it in GitHub Desktop.
Save SahilKadam/aea269f11edc6a259130cdd4e731a332 to your computer and use it in GitHub Desktop.
Given an array of distinct elements. The task is to find triplets in array whose sum is zero.
import java.util.*;
public class findTriplets{
public static void main(String []args){
int[] input = {1, -2, -1, 0, 2};
int result_n3 = findTriplets_n3(input);
int result_n2 = findTriplets_n2(input);
System.out.println(result_n3);
System.out.println(result_n2);
}
public static int findTriplets_n3(int[] input){
int count = 0;
for(int i=0; i<input.length-2; i++)
for(int j=i+1; j<input.length-1; j++)
for(int k=j+1; k<input.length; k++)
if(input[i]+input[j]+input[k] == 0){
count++;
System.out.println(input[i]+" "+input[j]+" "+input[k]);
}
return count;
}
public static int findTriplets_n2(int[] input){
HashMap<Integer, Integer> pairs = new HashMap<Integer, Integer>();
for(int i=0; i<input.length-1; i++)
for(int j=i+1; j<input.length; j++)
if(pairs.containsKey(input[i]+input[j]))
pairs.put(input[i]+input[j], (int) pairs.get(input[i]+input[j])+1);
else{
pairs.put(input[i]+input[j], 1);
}
int count = 0;
for(int i=0; i<input.length; i++){
if(pairs.containsKey(-1*input[i]))
count += (int) pairs.get(-input[i]);
}
return count/3;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment