1
+ package com .thealgorithms .misc ;
2
+
3
+ import java .util .ArrayList ;
4
+ import java .util .Arrays ;
5
+ import java .util .HashMap ;
6
+ import java .util .List ;
7
+
8
+ //In this problem, we are given an array of n integers and a target integer.
9
+ //We have to return a list containing all possible quadruplets from the given array which could add to get the target.
10
+
11
+ public class FourSumProblem {
12
+
13
+ //Best approach - Sorting and two-pointers
14
+ //Time Complexity - O(n^3)
15
+ //Space Complexity - O(n)
16
+ public List <List <Integer >> fourSum1 (int [] nums , int target ) {
17
+ List <List <Integer >> ans = new ArrayList <>();
18
+ Arrays .sort (nums );
19
+ for (int i = 0 ; i < nums .length -3 ; i ++) {
20
+ if (i > 0 && nums [i ] == nums [i -1 ]) continue ;
21
+ for (int j = i +1 ; j < nums .length - 2 ; j ++) {
22
+ if (j > i +1 && nums [j ] == nums [j -1 ]) continue ;
23
+ int left = j +1 ;
24
+ int right = nums .length -1 ;
25
+ while (left < right ) {
26
+ long sum = (long )nums [i ] + (long )nums [j ] + (long )nums [left ] + (long )nums [right ];
27
+ if (sum == target ) {
28
+ ans .add (Arrays .asList (nums [i ], nums [j ], nums [left ], nums [right ]));
29
+ while (left < right && nums [left ] == nums [left +1 ]) left ++;
30
+ while (left < right && nums [right ] == nums [right -1 ]) right --;
31
+ left ++; right --;
32
+ } else if (sum > target ) {
33
+ right --;
34
+ } else {
35
+ left ++;
36
+ }
37
+ }
38
+ }
39
+ }
40
+ return ans ;
41
+ }
42
+
43
+
44
+ //Another approach - Using HashMap
45
+ //Time Complexity - O(n^3)
46
+ //Space Complexity - O(n^2) (Storing the pair of sums)
47
+ public List <List <Integer >> fourSum2 (int [] nums , int target ) {
48
+ List <List <Integer >> ans = new ArrayList <>();
49
+ if (nums == null || nums .length < 4 ) return ans ;
50
+ Arrays .sort (nums );
51
+ for (int i = 0 ; i < nums .length - 3 ; i ++) {
52
+ if (i > 0 && nums [i ] == nums [i -1 ]) continue ;
53
+ for (int j = i + 1 ; j < nums .length - 2 ; j ++) {
54
+ if (j > i + 1 && nums [j ] == nums [j -1 ]) continue ;
55
+ HashMap <Integer , Integer > map = new HashMap <>();
56
+ for (int k = j + 1 ; k < nums .length ; k ++) {
57
+ int complement = target - nums [i ] - nums [j ] - nums [k ];
58
+ if (map .containsKey (complement )) {
59
+ ans .add (Arrays .asList (nums [i ], nums [j ], complement , nums [k ]));
60
+ while (k + 1 < nums .length && nums [k ] == nums [k + 1 ]) k ++;
61
+ }
62
+ map .put (nums [k ], k );
63
+ }
64
+ }
65
+ }
66
+ return ans ;
67
+ }
68
+ }
0 commit comments