Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,85 @@
</head>
<body>
<div class="container mt-5">
<h2>4Sum Better</h2>
<pre><code class="language-java">import java.util.*;

public class FourSumBetter {
public List<List<Integer>> fourSum(int[] nums, int target) {
int n = nums.length;
Set<List<Integer>> set = new HashSet<>();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
HashSet<Long> seen = new HashSet<>();
for (int k = j + 1; k < n; k++) {
long sum = (long) nums[i] + nums[j] + nums[k];
long needed = (long) target - sum;
if (seen.contains(needed)) {
List<Integer> temp = Arrays.asList(nums[i], nums[j], nums[k], (int) needed);
Collections.sort(temp);
set.add(temp);
}
seen.add((long) nums[k]);
}
}
}
return new ArrayList<>(set);
}

public static void main(String[] args) {
FourSumBetter sol = new FourSumBetter();
int[] nums = {1, 0, -1, 0, -2, 2}; // Example input
int target = 0;
List<List<Integer>> result = sol.fourSum(nums, target);
System.out.println("Quadruplets that sum to target: " + result);
}
}
</code></pre>

<h2>4Sum Optimal</h2>
<pre><code class="language-java">import java.util.*;

public class FourSumOptimal {
public List<List<Integer>> fourSum(int[] nums, int target) {
int n = nums.length;
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < n - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int k = j + 1;
int l = n - 1;
while (k < l) {
long sum = (long) nums[i] + nums[j] + nums[k] + nums[l];
if (sum == target) {
ans.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
while (k < l && nums[k] == nums[k + 1]) k++;
while (k < l && nums[l] == nums[l - 1]) l--;
k++;
l--;
}
else if (sum < target) {
k++;
}
else {
l--;
}
}
}
}
return ans;
}

public static void main(String[] args) {
FourSumOptimal sol = new FourSumOptimal();
int[] nums = {1, 0, -1, 0, -2, 2}; // Example input
int target = 0;
List<List<Integer>> result = sol.fourSum(nums, target);
System.out.println("Quadruplets that sum to target: " + result);
}
}
</code></pre>
<h2>3Sum Brute</h2>
<pre><code class="language-java">import java.util.*;

Expand Down