Last active
July 16, 2020 17:34
-
-
Save pratik7368patil/6e0df2dd228cbf1c9a1911f88c7ca2ff to your computer and use it in GitHub Desktop.
Four sum solution in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
class Pair { | |
int first; | |
int second; | |
public Pair(int first, int second) { | |
this.first = first; | |
this.second = second; | |
} | |
} | |
class twoPair { | |
// it's four pointer | |
int first; | |
int second; | |
int three; | |
int four; | |
public twoPair(int first, int second, int three, int four) { | |
this.first = first; | |
this.second = second; | |
this.three = three; | |
this.four = four; | |
} | |
} | |
class customComparatorTwoPair implements Comparator<twoPair> { | |
public int compare(twoPair p1, twoPair p2) { | |
if(p1.first == p2.first) { | |
if(p1.second == p2.second) { | |
if(p1.three == p2.three) { | |
return p1.four - p2.four; | |
} | |
return p1.three - p2.three; | |
} | |
return p1.second - p2.second; | |
} | |
return p1.first - p2.first; | |
} | |
} | |
class Main { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
int N = sc.nextInt(); | |
int K = sc.nextInt(); | |
int[] arr = new int[N]; | |
for(int i=0; i<N; i++) { | |
arr[i] = sc.nextInt(); | |
} | |
Arrays.sort(arr); | |
Map<Integer, ArrayList<Pair>> firstMap = new HashMap<>(); | |
for(int i=0; i<N; i++) { | |
for(int j=i+1; j<N; j++) { | |
addToPairList(arr[i]+arr[j], new Pair(i, j), firstMap); | |
} | |
} | |
findFourPairs(firstMap, K, N, arr); | |
} | |
public static void findFourPairs(Map<Integer, ArrayList<Pair>> firstMap, int K, int N, int[] arr) { | |
Map<twoPair, Integer> secMap = new TreeMap<>(new customComparatorTwoPair()); | |
for(int i=0; i<N; i++) { | |
for(int j=i+1; j<N; j++) { | |
int curSum = arr[i] + arr[j]; | |
int rem = K - curSum; | |
if(firstMap.containsKey(rem)){ | |
ArrayList<Pair> temp = firstMap.get(rem); | |
for(Pair p : temp) { | |
if(i != p.first && j != p.first && i != p.second && j != p.second && j<=p.first) | |
secMap.put(new twoPair(arr[i], arr[j], arr[p.first], arr[p.second]) ,1); | |
} | |
} | |
} | |
} | |
//System.out.println(secMap); | |
for(twoPair tp : secMap.keySet()) { | |
System.out.println(tp.first+ " "+tp.second+" "+tp.three+" "+tp.four); | |
} | |
} | |
public static void addToPairList(Integer key, Pair addThisPair, Map<Integer, ArrayList<Pair>> mapWithArrList) { | |
ArrayList<Pair> temp = mapWithArrList.get(key); | |
if(temp == null){ | |
temp = new ArrayList<Pair>(); | |
temp.add(addThisPair); | |
mapWithArrList.put(key, temp); | |
} else { | |
if(!temp.contains(addThisPair)) { | |
temp.add(addThisPair); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment