Problem solution · Java

4Sum

4Sum: a Java solution using sorting and greedy selection. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sorting and greedy selection
Source
walkccc LeetCode Solutions
Length
48 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sorting and greedy selection

For 4Sum, the implementation first exposes a useful order, then scans that order while making locally justified choices.

  1. Choose the key that reveals the greedy or grouping structure.
  2. Sort the relevant records by that key.
  3. Scan in order, maintaining the invariant that makes each local choice safe.

Code notes

  • 48 lines of Java from the credited upstream file 18.java.
  • The implementation visibly relies on sequence storage.
  • 4 loop blocks detected.

Complexity

Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full code4Sum · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public List<List<Integer>> fourSum(int[] nums, int target) {    List<List<Integer>> ans = new ArrayList<>();    Arrays.sort(nums);    nSum(nums, 4, target, 0, nums.length - 1, new ArrayList<>(), ans);    return ans;  }   // Finds n numbers that add up to the target in [l, r].  private void nSum(int[] nums, long n, long target, int l, int r, List<Integer> path,                    List<List<Integer>> ans) {    if (r - l + 1 < n || target < nums[l] * n || target > nums[r] * n)      return;    if (n == 2) {      // Similar to the sub procedure in 15. 3Sum      while (l < r) {        final int sum = nums[l] + nums[r];        if (sum == target) {          path.add(nums[l]);          path.add(nums[r]);          ans.add(new ArrayList<>(path));          path.remove(path.size() - 1);          path.remove(path.size() - 1);          ++l;          --r;          while (l < r && nums[l] == nums[l - 1])            ++l;          while (l < r && nums[r] == nums[r + 1])            --r;        } else if (sum < target) {          ++l;        } else {          --r;        }      }      return;    }     for (int i = l; i <= r; ++i) {      if (i > l && nums[i] == nums[i - 1])        continue;      path.add(nums[i]);      nSum(nums, n - 1, target - nums[i], i + 1, r, path, ans);      path.remove(path.size() - 1);    }  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗