Skip to content

Commit 4310b24

Browse files
committed
Update ThreeSumProblem
1 parent b4623c1 commit 4310b24

File tree

1 file changed

+163
-10
lines changed

1 file changed

+163
-10
lines changed

ThreeSumProblem

Lines changed: 163 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,157 @@
11

2+
********************************** I. Using Naive Approach ********************************************
3+
4+
/*
5+
* Question:
6+
Given an array of integers, return one set of 3 elements such that the 3 numbers add up to zero
7+
(VERY IMP NOTE: REPETITIONS OF ELEMENTS ARE ALLOWED)
8+
{10, -2, -1, 3} -> true
9+
{10, -2, 1} -> true -2 + 1 +1 =0
10+
*
11+
* Source: http://www.geeksforgeeks.org/find-a-triplet-that-sum-to-a-given-value/
12+
*
13+
* Algorithm : This is a THREE SUM PROBLEM:
14+
* Generate all possible three set sums and check whether any of them matches with the given sum.
15+
* 1. Run first loop from i to arraySize
16+
* 1.1 Run second loop from j=i+1 to arraySize
17+
* 1.1.1 Run third loop from k=j+1 to arraySize
18+
* Check if array[i]+array[j]+array[k]=Sum
19+
*
20+
*/
21+
22+
23+
package ThreeSumProblem;
24+
25+
import java.util.Scanner;
26+
27+
public class UsingNaiveApproach {
28+
public static void main(String[] args) {
29+
Scanner in = new Scanner(System.in);
30+
try{
31+
System.out.println("Enter the number of elements in the array");
32+
int n = in.nextInt();
33+
int[] array = new int[n];
34+
System.out.println("Enter the elements of the array");
35+
for(int i=0;i<n;i++)
36+
array[i]=in.nextInt();
37+
System.out.println("Enter the sum that you need to find in the array");
38+
int sum = in.nextInt();
39+
System.out.println("The elements whose addition returns the sum are: ");
40+
usingNaiveApproach(array,sum);
41+
}
42+
finally{
43+
in.close();
44+
}
45+
}
46+
47+
private static void usingNaiveApproach(int[] array, int sum) {
48+
outerloop: // label the outer loop
49+
for(int i=0;i<array.length;i++)
50+
for(int j=i+1;j<array.length;j++)
51+
for(int k=j+1;k<array.length;k++)
52+
if(array[i]+array[j]+array[k]==sum){
53+
System.out.println(array[i]+" "+array[j]+" "+array[k]);
54+
break outerloop; // break the outer loop so that all internal loops are also broken
55+
}
56+
}
57+
58+
}
59+
/*
60+
* Analysis:
61+
* Time Complexity = O(n^3)
62+
* Space Complexity = O(1)
63+
*/
64+
65+
********************************** II. Using Sorting ***********************************************
66+
67+
/*
68+
* Question:
69+
Given an array of integers, return one set of 3 elements such that the 3 numbers add up to zero
70+
(VERY IMP NOTE: REPETITIONS OF ELEMENTS ARE ALLOWED)
71+
{10, -2, -1, 3} -> true
72+
{10, -2, 1} -> true -2 + 1 +1 =0
73+
*
74+
* Source: http://www.geeksforgeeks.org/find-a-triplet-that-sum-to-a-given-value/
75+
*
76+
* Algorithm : This is a THREE SUM PROBLEM:
77+
* Sort the array and then apply the Two Sum Logic
78+
* 1. Sort the array
79+
* 2. Run a loop starting from i=0 to (arraySize-2)
80+
* 2.1 Take a fixed element as fixedElement = array[i]
81+
* 2.2 Find the other two elements from the SORTED ARRAY CORNERS
82+
* low = [i+1] // Next Element
83+
* high = [arraySize-1] // last element of the array
84+
* 2.2.1 while(low<high)
85+
* Check if(fixed+low+high == sum). If yes then print the elements and break
86+
* if(fixed+low+high < sum). Then low++
87+
* if(fixed+low+high > sum). Then high--
88+
*/
89+
90+
91+
package ThreeSumProblem;
92+
93+
import java.util.Arrays;
94+
import java.util.Scanner;
95+
96+
public class UsingSorting {
97+
public static void main(String[] args) {
98+
Scanner in = new Scanner(System.in);
99+
try{
100+
System.out.println("Enter the number of elements in the array");
101+
int n = in.nextInt();
102+
int[] array = new int[n];
103+
System.out.println("Enter the elements of the array");
104+
for(int i=0;i<n;i++)
105+
array[i]=in.nextInt();
106+
System.out.println("Enter the sum that you need to find in the array");
107+
int sum = in.nextInt();
108+
System.out.println("The elements whose addition returns the sum are: ");
109+
usingSorting(array,sum);
110+
}
111+
finally{
112+
in.close();
113+
}
114+
}
115+
116+
private static void usingSorting(int[] array, int sum) {
117+
int low=0;
118+
int high=0;
119+
/* Sort the elements */
120+
Arrays.sort(array);
121+
/* Now fix the first element one by one and find the
122+
other two elements */
123+
outerloop:
124+
for(int i=0;i<(array.length-2);i++){
125+
// To find the other two elements, start two index variables
126+
// from two corners of the array and move them toward each
127+
// other
128+
low=i+1;
129+
high = array.length-1;
130+
while(low<high){
131+
if(array[i]+array[low]+array[high]==sum){
132+
System.out.println(array[i]+" "+array[low]+" "+array[high]);
133+
break outerloop;
134+
}
135+
if(array[i]+array[low]+array[high]<sum)
136+
low++;
137+
if(array[i]+array[low]+array[high]>sum)
138+
high--;
139+
140+
}
141+
}
142+
}
143+
144+
145+
146+
}
147+
/*
148+
* Analysis:
149+
* Time Complexity = O(n^2) due to nested for and while loop
150+
* Space Complexity = O(1)
151+
*/
152+
153+
154+
**************************** III Solving Three Sum Problem Using HashMap ****************************************
2155

3156
VERY IMP NOTE: Time Complexity of Three Sum Problem using:
4157
1. HashMap = O(n^3)
@@ -8,7 +161,6 @@ we can SAFELY use HashSet.
8161
2. HashSet = O(n^2)
9162
HashSet is used when array elements are unique.
10163

11-
**************************** I. Solving Three Sum Problem Using HashMap ****************************************
12164
/*
13165
* Question:
14166
Given an array of integers, return one set of 3 elements such that the 3 numbers add up to zero
@@ -50,7 +202,7 @@ public static void main(String[] args) {
50202
array[i]=in.nextInt();
51203
System.out.println("Enter the sum that you need to find in the array");
52204
int sum = in.nextInt();
53-
System.out.println("The elements whose additon returns the sum are: ");
205+
System.out.println("The elements whose addition returns the sum are: ");
54206
findThreeSumUsingHashMap(array,sum);
55207
}
56208
finally{
@@ -66,9 +218,9 @@ private static void findThreeSumUsingHashMap(int[] array, int sum) {
66218
// iterate through the array elements and check whether the third is in the HashMap
67219
outerloop: // using label in Java to break the outer loop
68220
for(int i=0;i<array.length;i++)
69-
for(int j=i;j<array.length;j++)
70-
if(map.containsValue(-(array[i]+array[j]))){ // containsValue time complexity is O(n)
71-
System.out.print(array[i]+" "+array[j]+" "+(-(array[i]+array[j])));
221+
for(int j=i+1;j<array.length;j++) // start from the next element
222+
if(map.containsValue(sum-(array[i]+array[j]))){ // containsValue time complexity is O(n)
223+
System.out.print(array[i]+" "+array[j]+" "+(sum-(array[i]+array[j])));
72224
break outerloop; // we can use labels to break directly the outer loop (which in turn breaks inner loop)
73225
} // Otherwise, we would have to implement some mechanism to break both the loops simultaneously
74226

@@ -80,7 +232,8 @@ private static void findThreeSumUsingHashMap(int[] array, int sum) {
80232
* Space Complexity = O(n)
81233
*/
82234

83-
**************************** I. Solving Three Sum Problem Using HashSet ****************************************
235+
236+
**************************** IV. Solving Three Sum Problem Using HashSet ****************************************
84237
/*
85238
* Question:
86239
Given an array of integers, return one set of 3 elements such that the 3 numbers add up to zero
@@ -122,7 +275,7 @@ public static void main(String[] args) {
122275
array[i]=in.nextInt();
123276
System.out.println("Enter the sum that you need to find in the array");
124277
int sum = in.nextInt();
125-
System.out.println("The elements whose additon returns the sum are: ");
278+
System.out.println("The elements whose addition returns the sum are: ");
126279
findThreeSumUsingHashSet(array,sum);
127280
}
128281
finally{
@@ -138,9 +291,9 @@ private static void findThreeSumUsingHashSet(int[] array, int sum) {
138291
// iterate through the array elements and check whether the third is in the HashMap
139292
outerloop: // using label in Java to break the outer loop
140293
for(int i=0;i<array.length;i++)
141-
for(int j=i;j<array.length;j++)
142-
if(set.contains(-(array[i]+array[j]))){ // time complexity of contains method of HashSet is O(1)
143-
System.out.print(array[i]+" "+array[j]+" "+(-(array[i]+array[j])));
294+
for(int j=i+1;j<array.length;j++) // start from the next element
295+
if(set.contains(sum-(array[i]+array[j]))){ // time complexity of contains method of HashSet is O(1)
296+
System.out.print(array[i]+" "+array[j]+" "+(sum-(array[i]+array[j])));
144297
break outerloop; // we can use labels to break directly the outer loop (which in turn breaks inner loop)
145298
} // Otherwise, we would have to implement some mechanism to break both the loops simultaneously
146299

0 commit comments

Comments
 (0)