@@ -8,37 +8,37 @@ public class FourSumProblem {
88
99 public static List <List <Integer >> fourSum (int [] nums , int target ) {
1010 List <List <Integer >> result = new ArrayList <>();
11-
11+
1212 if (nums == null || nums .length < 4 ) {
1313 return result ; // if array is too small to have 4 numbers, return empty result
1414 }
15-
15+
1616 // Sort the array first
1717 Arrays .sort (nums );
18-
18+
1919 // Iterate through the array, fixing the first two elements
2020 for (int i = 0 ; i < nums .length - 3 ; i ++) {
2121 if (i > 0 && nums [i ] == nums [i - 1 ]) continue ; // Skip duplicates for the first element
2222
2323 for (int j = i + 1 ; j < nums .length - 2 ; j ++) {
2424 if (j > i + 1 && nums [j ] == nums [j - 1 ]) continue ; // Skip duplicates for the second element
25-
25+
2626 // Use two pointers for the remaining two elements
2727 int left = j + 1 ;
2828 int right = nums .length - 1 ;
29-
29+
3030 while (left < right ) {
3131 int sum = nums [i ] + nums [j ] + nums [left ] + nums [right ];
32-
32+
3333 if (sum == target ) {
3434 // If we found a quadruplet, add it to the result list
3535 result .add (Arrays .asList (nums [i ], nums [j ], nums [left ], nums [right ]));
36-
36+
3737 // Skip duplicates for the third element
3838 while (left < right && nums [left ] == nums [left + 1 ]) left ++;
3939 // Skip duplicates for the fourth element
4040 while (left < right && nums [right ] == nums [right - 1 ]) right --;
41-
41+
4242 // Move the pointers
4343 left ++;
4444 right --;
@@ -52,7 +52,7 @@ public static List<List<Integer>> fourSum(int[] nums, int target) {
5252 }
5353 }
5454 }
55-
55+
5656 return result ;
5757 }
5858}
0 commit comments