6/19/2017

Leetcode 15. 3Sum solution with detail explanation

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.


Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Keywords
Before 3sum, there is a two sum problem. 
Literally, we can make the 3sum as another 2 sum problem. 
For example, I need to have:

a + b + c = 0;
transfer it into:
a + b = -c;

There are some ways to solve this problem. 

#1: Easy Understanding But Dumb:
Thinking in an easy way to solve this problem, I gonna quick create 3 pointers in the array:
[ -1, 0, 1, 2, -1, 4]
   ^   ^  ^
   A  B C
First round, fixed A and B, let C go through all rest of the numbers and check if( A + B + C == 0) every time.
Second round, keep A, move B to the next number, here is 1, iterate C and check A + B + C =0.
[ -1, 0, 1, 2, -1, 4]
   ^       ^  ^
   A       B C
After B and C iterate all items, move A to 0, and restart it. Until pointer A moves to 2, the algorithm checks all possibilities in the array.
However, it would cost cubic time complexity which is not smart enough.


#2: The Better Way costs O(n^2) like following:

Solution:



Reference: 
Interview Question: Three Sum https://youtu.be/-AMHUdZc9ss

No comments:

Post a Comment