~/coding-interview/leetcode-four-sum.md

Four Sum - Leet Code Solution

// TL;DR

Sort the array, fix the first two elements with nested loops, then use two pointers for the remaining two. Skip duplicates at each level. O(n^3) time.

Four Sum - Leet Code Solution

Problem Statement

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Notice that the solution set must not contain duplicate quadruplets.

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Input: nums = [], target = 0
Output: []

Solution

Lets take help of our two-sum problem.

Code

private List<List<Integer>> twoSum(int[] nums, int target, int start) {
  List<List<Integer>> res = new ArrayList<>();
  int l = start;
  int r = nums.length-1;
  while (l < r) {
    
    /**
      * second conditions are for avoiding duplicates.
      */
    
    if (nums[l] + nums[r] < target || (l > start && nums[l-1] == nums[l])) {
      l++;
    }
    else if (nums[l] + nums[r] > target || (r < nums.length-1 && nums[r] == nums[r+1])) {
      r--;
    }
    else {
      List<Integer> t = new ArrayList<>();
      t.add(nums[l]);
      t.add(nums[r]);
      res.add(t);
      l++;
      r--;
    }
  }
  
  return res;
}

// -2 -1 0 0 1 2
private List<List<Integer>> helper(int[] nums, int target, int startIndex, int k) {
  List<List<Integer>> res = new ArrayList<>();
  
  if (startIndex >= nums.length || nums[startIndex] * k > target || target > nums[nums.length - 1] * k) {
    return res;
  }
  else if (k == 2) {
    return twoSum(nums, target, startIndex);
  }
  else {
    for (int i=startIndex; i<nums.length; i++) {
      //This condition is to avoid duplicates
      if (i == startIndex || nums[i] != nums[i-1]) {
        List<List<Integer>> res2 = helper(nums, target-nums[i], i+1, k-1);
        for (List<Integer> t : res2) {
          List<Integer> newRes = new ArrayList<>();
          newRes.add(nums[i]);
          newRes.addAll(t);
          
          res.add(newRes);
        }
      }
    }
  }
  
  return res;
}

public List<List<Integer>> fourSum(int[] nums, int target) {
  //sorting will help in avoiding duplicates in easy manner
  Arrays.sort(nums);
  
  return helper(nums, target, 0, 4);
}
	

Complexity

O(n^2)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Replace all spaces in a string with %20

Replace all spaces in a string with %20

Problem Statement Replace all spaces in a string with ‘%20’ (three characters…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…