www.fatihkabakci.com

Personal Website and Computer Science TUR EN

Interview Question 4Sum

Last update: 1/1/2017 11:49:00 PM

By Fatih KABAKCI

The problem is to find out all unique quadruplets in the array which the sum of any 4 elements is a specified target. The solution of the problem is almost same with the solution of the problem 3Sum. The only difference between them is number of the elements in the list which have been gathered, and the target does not have to be zero as 3Sum does. However, by this way, it is similar to solution of the problem 3Sum Closest..

So, in order to understand this problem, it is better idea to understand 3Sum Problem.

Problem #18 - 4Sum

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

Difficulty: Medium

Solution in Java

package com.fatihkabakci.Medium._4Sum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @author fkabakci
 * 
 * Problem Description: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? 
 * Find all unique quadruplets in the array which gives the sum of target.
 * 
 * Note: The solution set must not contain duplicate quadruplets.
 *
 * For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
 *
 *	A solution set is:
 * 		[
 *        [-1,  0, 0, 1],
 *        [-2, -1, 1, 2],
 *        [-2,  0, 0, 2]
 * 	    ]
 * 
 * Solution:
 * 
 * The main idea of the solution is as same as the solution of the problem 3Sum.
 * 
 * 1. Sort the input array.
 * 2. Start with getting first, second, third and last element.
 * 3. Add up them.
 * 4. If sum equals to target,
 * 		 then add them into the list, and pass to fourth one, and previous one element of the last one.
 * 	  If sum is less than zero,
 * 	     then close to higher one. (Pass to fourth one by increasing loop variable k)
 * 	  If sum is greater than zero,
 * 		 then close to lower one. (Pass to previous one of the last one by decreasing loop variable m)
 * 5. Lastly, get rid of duplicated elements by using Collection Set.
 */

public class _4Sum {
	public List<List<Integer>> fourSum(int[] nums, int target) {
		if (nums.length < 4)
			return new ArrayList<List<Integer>>();
		
		Arrays.sort(nums);
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		
		int i = 0, j = 0, k = 1, m;
		while (i < nums.length - 1 && j < k) {
			if(++j == nums.length) {
				j = (++i) + 1;
			}
			k = j + 1;
 			m = nums.length - 1;
			while (k < m) {
				int sum = nums[i] + nums[j] + nums[k] + nums[m];
				if (sum == target) {
					List<Integer> tsum = new ArrayList<Integer>();
					tsum.add(nums[i]);
					tsum.add(nums[j]);
					tsum.add(nums[k]);
					tsum.add(nums[m]);
					list.add(tsum);
					k++;
					m--;
				} else if (sum < target)
					k++;
				else
					m--;
			}
		}
		Set<List<Integer>> set = new LinkedHashSet<List<Integer>>(list);
		return new ArrayList<List<Integer>>(set);
	}

	public static void main(String[] args) {
		_4Sum i = new _4Sum();
		List<List<Integer>> l = i.fourSum(new int[] {1, 0, -1, 0, -2, 2}, 0);
		Iterator<List<Integer>> it = l.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Similar Problems

#15 3Sum

#16 3Sum Closest

There has been no comment yet

Name:


Question/Comment
   Please verify the image




The Topics in Computer Science

Search this site for





 

Software & Algorithms

icon

In mathematics and computer science, an algorithm is a step-by-step procedure for calculations. Algorithms are used for calculation, data processing, and automated reasoning.

Programming Languages

icon

A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. It can be used to create programs to control the behavior of a machine. Java,C, C++,C#

Database

icon

A database is an organized collection of data. The data are typically organized to model aspects of reality in a way that supports processes requiring information.

Hardware

icon

Computer hardware is the collection of physical elements that constitutes a computer system. Computer hardware refers to the physical parts or components of a computer such as the monitor, memory, cpu.

Web Technologies

icon

Web development is a broad term for the work involved in developing a web site for the Internet or an intranet. Html,Css,JavaScript,ASP.Net,PHP are one of the most popular technologies. J2EE,Servlet, JSP,JSF, ASP

Mobile Technologies

icon

Mobile application development is the process by which application software is developed for low-power handheld devices, such as personal digital assistants, enterprise digital assistants or mobile phones. J2ME

Network

icon

A computer network or data network is a telecommunications network that allows computers to exchange data. In computer networks, networked computing devices pass data to each other along data connections.

Operating Systems

icon

An operating system is software that manages computer hardware and software resources and provides common services for computer programs. The OS is an essential component of the system software in a computer system. Linux,Windows

Computer Science

icon

Computer science is the scientific and practical approach to computation and its applications.A computer scientist specializes in the theory of computation and the design of computational systems.