Personal Website and Computer Science TUR EN

Interview Question 3Sum

Last update: 12/28/2016 9:37:00 AM


The problem is to figure out all unique triplets in a given array which sum of any 3 elements in that array is zero. O(n2) is accepted.

Problem #15 - 3Sum

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

Difficulty: Medium

Solution in Java

When the problem is seen, the laziest solution would be brute force which is O(n3) algorithm complexity. Designing three loop for each element gives O(n3) complexity as the following.

Brute Force - O(n3)

This method is considered Time Limit Exceeded on LeetCode platform. However it might be still good idea to understand problem from beginning, basic point.

public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> l = new ArrayList<List<Integer>>();

		for (int i = 0; i < nums.length; i++) {
			int a = nums[i];
			for (int j = i + 1; j < nums.length; j++) {
				int b = nums[j];
				for (int k = j + 1; k < nums.length; k++) {
					int c = nums[k];
					if (a + b + c == 0) {
						List<Integer> sl = new ArrayList<Integer>();						
		l = new ArrayList<List<Integer>>(new LinkedHashSet<List<Integer>>(l));
		return l;

However, the solution which is above, would not be acceptable well enough. Because, the entire code looks all possibilities even though some of them are unnecessary to look for. So, what we can do is to try to diminish complexity.

Better Solution - O(n2)

We might start to sort the input array first. Then we can get 3 elements from first, second and last one. In regard to result of sum of them, which might be zero, less than zero or greater than zero, we move loop variables to up or down. Here might be better solution as below.

For example,

As seen above, we can code the solution with O(n2) complexity in Java as below.

package com.fatihkabakci.Medium._3Sum;

import java.util.ArrayList;
import java.util.Arrays;
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 in S such that 
 * a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
 *  For example, given array S = [-1, 0, 1, 2, -1, -4],
 *	A solution set is:
 *	[
 *	  [-1, 0, 1],
 *	  [-1, -1, 2]
 *	]
 * Solution:
 * 1. Sort the input array.
 * 2. Start with getting first, second and last element.
 * 3. Add up them.
 * 4. If sum equals to zero,
 * 		 then add them into the list, and skip to third one, and previous one element of the last one.
 * 	  If sum is less than zero,
 * 	     then close to higher one. (Skip to third one by increasing loop variable j)
 * 	  If sum is greater than zero,
 * 		 then close to lower one. (Skip to previous one of the last one by decreasing loop variable k)
 * 5. Lastly, get rid of duplicated elements by using Collection Set.

public class _3Sum {
	public List<List<Integer>> threeSum(int[] nums) {
		if (nums.length < 3)
			return new ArrayList<List<Integer>>();
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		int i = 0, j, k;
		while (i < nums.length - 1) {
			j = i + 1;
			k = nums.length - 1;
			while (j < k) {
				int sum = nums[i] + nums[j] + nums[k];
				if (sum == 0) {
					List<Integer> tsum = new ArrayList<Integer>();
				} else if (sum < 0)
		Set<List<Integer>> set = new LinkedHashSet<List<Integer>>(list);
		return new ArrayList<List<Integer>>(set);

Similar Problems

#16 3Sum Closest

#18 4Sum

There has been no comment yet


   Please verify the image

The Topics in Computer Science

Search this site for


Software & Algorithms


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


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#



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.



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


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,Spring Boot, Servlet, JSP,JSF, ASP

Mobile Technologies


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



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


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


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.